PHP in Amazon Lambda

Clone or Download this GitHub Repo

Make new folder lambda in current working directory of EC2 server
# mkdir lambda

Upload 2 files from zip to Amazon EC2 server Instance in folder lambda

– index.js
– php (binary)


'use strict';
exports.handler = function(event, context, callback) {
var exec = require('child_process').exec;

  exec('./php -v', function (error, stdout, stderr) {
      console.log('stdout: ' + stdout);
      console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('Exec error: ' + error);

Go inside folder lambda

# cd lambda
# zip -r ../ *

Copy for AWS S3 bucket

# aws s3 cp ../ s3://bucket-name/

How to install AWS CLI?

Create new Lambda Function from AWS Console with NodeJS Runtime*

Name*: phpv
Runtime*: Node.js 4.3
Code entry type: Upload a file from Amazon S3
S3 link URL*:

Handler*: index.handler
Role*: Lambda Basic Execution

All other info will be default**

Save & Test

“PHP 5.6.5 (cli) (built: Jul 21 2015 18:56:08) \nCopyright (c) 1997-2014 The PHP Group\nZend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies\n”

Free SSL Certbot

Certbot, It was Let’s Encrypt Client previously. Automatically enable HTTPS on your website with EFF’s Certbot, deploying Let’s Encrypt certificates.

Server Support

– Apache
– Nginx
– Haproxy
– Plesk

OS Support

– Web Hosting Service
– Debian 7 (wheezy)
– Debian 8 (jessie)
– Debian 9 (stretch)
– Debian testing/unstable
– Debian (other)
– Ubuntu 17.04 (zesty)
– Ubuntu 16.10 (yakkety)
– Ubuntu 16.04 (xenial)
– Ubuntu 14.04 (trusty)
– Ubuntu (other)
– Gentoo
– Arch Linux
– Fedora 24+
– CentOS 6
– RHEL 6
– CentOS/RHEL 7
– FreeBSD
– OpenBSD 5.9
– OpenBSD 6.0+
– OpenBSD (other)
– macOS
– Devuan Jessie 1.0
– Devuan (other)
– Other UNIX
– Non-UNIX

Install on Ubuntu 17.04 (zesty) Apache

$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-apache

Get Started

$ sudo certbot --apache

$ sudo certbot --apache certonly

Automating renewal

$ sudo certbot renew --dry-run

$ sudo crontab -e

30 1 * * * /usr/bin/certbot renew --quiet

It will run renewal command at 1:30 am, every day.

Amazon Simple Notification Service Command Lines

Install the AWS CLI Using the Bundled Installer

Download the AWS CLI Bundled Installer.

# curl “” -o “”
# unzip
# chmod a+x ./awscli-bundle/install
# ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws

Configure AWS CLI

# aws configure
Default region name [None]: us-east-1
Default output format [None]: json

# cat ~/.aws/credentials


# cat ~/.aws/config


AWS SNS Common actions

– Create a communication channel to send messages and subscribe to notifications
– Create a platform application for mobile devices
– Subscribe an endpoint to a topic to receive messages published to that topic
– Publish a message to a topic or as a direct publish to a platform endpoint
– Publish a text message (SMS) to a phone number

Create AWS SNS Topic

# aws sns create-topic –name My-Blog
“TopicArn”: “arn:aws:sns:us-east-1:xxxxxxxxxxxx:My-Blog”

Now you can subscribe to Topic using these protocols

http, https, email, email-json, sms, sqs, application, lambda

check more here:

Subscribe to AWS SNS Topic by email

# aws sns subscribe –topic-arn arn:aws:sns:us-east-1:xxxxxxxxxxxx:My-Blog –protocol email –notification-endpoint
“SubscriptionArn”: “pending confirmation”

AWS SNS Confirm

After Subscription Confirmed it provide SubscriptionArn like arn:aws:sns:us-east-1:xxxxxxxxxxxx:My-Blog:4e2a8654-6b5d-43fe-bf14-2237c8c849f7

AWS SNS Pending Confirm

Subscribe to AWS SNS Topic by Mobile (SMS)

# aws sns subscribe –topic-arn arn:aws:sns:us-east-1:xxxxxxxxxxxx:My-Blog –protocol sms –notification-endpoint 919912345678
“SubscriptionArn”: “arn:aws:sns:us-east-1:xxxxxxxxxxxx:My-Blog:a0bb38ca-ece1-4adb-897b-5a21010889e9”

Publish message to Topic

# aws sns publish –topic-arn arn:aws:sns:us-east-1:xxxxxxxxxxxx:My-Blog –message “Welcome to My Blog!”
“MessageId”: “9f280eb4-b561-5d34-b8c3-5f3be74515b2”

AWS SNS Push Message


Unsubscribe to AWS SNS Topic

# aws sns unsubscribe –subscription-arn “arn:aws:sns:us-east-1:xxxxxxxxxxxx:My-Blog:4e2a8654-6b5d-43fe-bf14-2237c8c849f7”

You can find Available Commands for AWS SNS here

Delete AWS SNS Topic

# aws sns delete-topic –topic-arn “arn:aws:sns:us-east-1:xxxxxxxxxxxx:My-Blog”

Uninstalling AWS CLI

# rm -rf /usr/local/aws
# rm /usr/local/bin/aws

Install the AWS Command Line Interface on Microsoft Windows

Amazon DynamoDB PHP CRUD using aws.phar

DynamoDB is fully managed, fast and low cost NoSQL database service by Amazon. DynamoDB allows you to offload the administrative operations and scale highly distributed database cluster.

The AWS SDK PHP enables you to use Amazon Web Services like Amazon S3, EC2, RDS, CloudFront, Redshift, DynamoDB, Push Notification Service (SNS) and more from your PHP code project.

AWS.PHAR Now Download aws-php-sdk Packaged Phar from

# wget

You can also download the packaged phar here

Include the SDK in your PHP project require ‘/path/to/aws.phar’;

Now download simple dynamodb-php-wrapper from here


require_once 'aws.phar';
require_once 'DynamoDBWrapper.php'; 

$ddb = new DynamoDBWrapper(array(
    'region' => 'us-east-1'


$result = $ddb->createTable(‘Session’, ‘UserId::N’);
// Create a table ‘Session’, which has a hash key ‘UserId’ as NUMBER.


$result = $ddb->deleteTable(‘Session’);


$item = array(
‘UserId’ => 1,
‘Name’ => ‘Sandeep’,
$result = $ddb->put(‘Session’, $item);


$key = array(
‘UserId’ => 1,
$update = array(
‘Name’ => array(‘PUT’, ‘SVNLabs’)
$result = $ddb->update(‘Session’, $key, $update);


$key = array(
‘UserId’ => 1,
$result = $ddb->delete(‘Session’, $key);


$keyConditions = array(
‘UserId’ => 1,
$result = $ddb->query(‘Session’, $keyConditions);


$filter = null;

$result = $ddb->scan(‘Session’, $filter, 1000);

Scan with between date filter

$filter = array(
‘userType’ => “member”,
“date” => array(“BETWEEN”, array(“2016/08/01″,”2016/08/17”))
$result = $ddb->scan(“Session”, $filter, 1000);

Other Links

Install AWStats with GeoIP Plugin

AWStats is a free analytic tool that generates web, streaming, ftp or mail server statistics, graphically. There are many log analyzer but AWStats is open source Web analytics reporting tool, It can analyze log files from Apache, WebStar, IIS.

Installing AWStats on ubuntu 12.04

# apt-get install awstats

Configuring for replace with your real domain

# cp /etc/awstats/awstats.conf /etc/awstats/
# vi /etc/awstats/

Check you have below settings in /etc/awstats/


Generate stats for AWStats for /var/log/apache2/access.log file (Make sure you have fresh log file)

# /usr/lib/cgi-bin/ -update

configuration Apache2 with password

# htpasswd -c /etc/awstats/awstats.pwd admin
# chmod 755 /etc/awstats/awstats.pwd

# vi /etc/apache2/sites-available/awstats

<VirtualHost *:80>
DocumentRoot /var/www
ErrorLog ${APACHE_LOG_DIR}/error_awstats.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access_awstats.log combined
<Directory “/usr/lib/cgi-bin/”>
<Files “”>
Options +ExecCGI
Alias /awstats-icon/ “/usr/share/awstats/icon/”
<Directory /usr/share/awstats/icon>
Options None
AllowOverride All
Order allow,deny
Allow from all
RewriteEngine on
RewriteRule /awstats-icon – [L]
RewriteCond %{QUERY_STRING} !^(.*&)?framename=index(&.*)?$
RewriteCond %{QUERY_STRING} ^(.*&)?framename=.*(&.*)?$
RewriteRule /(.*) /usr/lib/cgi-bin/ [L]
RewriteCond %{QUERY_STRING} ^(.*&)?config=([^&]*)(&(.*))?$
RewriteRule /.* /%2?%1%4 [R,L]
RewriteRule /$ / [R,L]
RewriteRule /([^/]*)(/.*)? /usr/lib/cgi-bin/$1 [QSA,L]
<Location />
SetHandler cgi-script
Satisfy any
Order deny,allow
Deny from all
AuthType Basic
AuthName “AWStats Access”
AuthUserFile /etc/awstats/awstats.pwd
require valid-user
<LocationMatch /(?!|robots.txt)$>
Require user admin
<Location /awstats-icon>
SetHandler None
Allow from all

Enable Virtual Host

# a2ensite awstats
# apache2ctl configtest
# /etc/init.d/apache2 reload

Auto update stats

# crontab -e

*/10 * * * * /usr/share/awstats/tools/
10 03 * * * /usr/share/awstats/tools/
*/10 * * * * /usr/lib/cgi-bin/ -update > /dev/null

Set proper permission on logs

# sudo chmod 644 -R /var/log/apache2/*
# chmod 644 /var/log/apache2

# vi /etc/logrotate.d/apache2   (Replace create 640 root adm with create 644 root adm)

Install GeoIP for AWStats

# apt-get install build-essential zlib1g-dev apg libgeo-ipfree-perl libnet-ip-perl libnet-dns-perl liburi-perl apache2-utils

# cd /usr/src/
# wget
# tar xvzf zlib-1.2.8.tar.gz
# cd zlib-1.2.8
# ./configure –prefix=/usr/local/zlib && make && make install

# wget
# tar xzvf GeoIP-latest.tar.gz
# cd GeoIP-1.6.0
# ./configure && make && make install

# cpan
> install YAML
> install Geo::IP Geo::IPfree Geo::IP::PurePerl URI::Escape Net::IP Net::DNS Net::XWhois Time::HiRes Time::Local
> quit

# cd /usr/src/
# wget
# gzip -d GeoLiteCity.dat.gz
# cp GeoLiteCity.dat /usr/share/GeoIP/GeoLiteCity.dat

Enable AWSTAT configuation for LoadPlugin

# vi /etc/awstats/

Remove comment from /etc/awstats/

LoadPlugin=”geoip GEOIP_STANDARD /usr/share/GeoIP/GeoIP.dat”
LoadPlugin=”geoip_city_maxmind GEOIP_STANDARD /usr/share/GeoIP/GeoLiteCity.dat”

# /etc/init.d/apache2 reload

AWStats will run here




Error opening /usr/share/GeoIP/GeoIPCity.dat at /usr/local/share/perl/5.14.2/Geo/IP/ line [file name in /usr/share/GeoIP]

Make sure you have all files in folder /usr/share/GeoIP/GeoLiteCity.dat else copy

# cp /usr/share/GeoIP/GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat


Other log file analysis and reporting tools

Create Website Thumbnails using PhantomJS

Hope you read my old article “Create WebThumb using LAMP”, it used for creating web thumbnails from Xvfb virtual framebuffer that is more time and resource consuming.

Shell Script with Xvfb try to open web browsers in real remote server to capture web-thumbs…

That whole setup might take a full day and image quality is very bad….

Thanks to PhantomJS

PhantomJS is a headless WebKit with JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.

Simple Javascript example

console.log(‘Loading a web page’);
var page = require(‘webpage’).create();
var url = ‘’;, function (status) {
//Page is loaded!


– Headless Website Testing
– Screen Capture
– Page Automation
– Network Monitoring

Fork on Github

PhantomJS is using WebKit for a real layout and rendering engine, it can be used to capture web page as screenshot or PDF files. PhantomJS can render anything on the web page, it can be used to convert contents in HTML/CSS, SVG and Canvas.

// Thumbnail of Webpage using webthumb.js

var page = require('webpage').create(),
    system = require('system'),

if (system.args.length !== 3) {
    console.log('Usage: webthumb.js webURL filename');
    console.log('Usage: webthumb.js svnlabs.png');
} else {
    weblink = system.args[1];
    fname = system.args[2];    
    page.viewportSize = { width: 320, height: 480 };, function (status) {
    if (status !== 'success') {
        console.log('Unable to open webpage!');
    } else {
    window.setTimeout(function () {
    }, 3000);

Download webthumb.js

# phantomjs webthumb.js svnlabs.png
# phantomjs webthumb.js svnlabs.pdf

You can even capture webpage as good quality PDF file 😉



You can also use examples/rasterize.js for same sort of functions 😉

# phantomjs examples/rasterize.js svnlabs.png
# phantomjs examples/rasterize.js ‘’ svnlabs.pdf

rasterize.js – rasterizes a web page to image or PDF
render_multi_url.js – renders multiple web pages to images
technews.js – captures Google News as a PNG image

Upload Large Files from Amazon S3 Bucket to Dropbox Folder

Dropbox Uploader is a BASH script (only needs cURL) which can be used to upload, download, list or delete files from Dropbox, an online file sharing, synchronization and backup service.


Amazon S3 to Dropbox
Amazon S3 to Dropbox

Secure:It’s not required to provide your username/password to this script, because it uses the official Dropbox API for authentication process.


# chmod +x
# ./

It will ask “App key”, “App secret” and “Access level (App folder or Full Dropbox)”

As shell script authorize token…

Please visit this URL from your Browser, and allow Dropbox Uploader
to access your DropBox account:


Dropbox token for Command Line
Dropbox token for Command Line

If everything go well …

> Access Token request… OK

Setup completed!

Now you can download Amazon S3 Bucket files on server using “wget” then you can run command like…

# ./ upload /var/www/aws/s3/svnlabs.mp4 /DROPBOX-FOLDER/svnlabs.mp4

I have uploaded media file upto 500MB on dropbox successfully using this shell script 😉

Alternate Options:

You can try Node.js for reading files from Amazon S3 and then upload to Dropbox

Useful JavaScript Tools—Amazon-S3

Amazon S3 Cloud HTML5 MP3 Player

Amazon S3 Cloud HTML5 Player plugin that allows you to link to your amazon S3 bucket and sets up a HTML5 Player playlist (horizontal or vertical). This plugin will support MP3 files only.

Amazon S3 Cloud HTML5 MP3 Player is not associated in any way to

Get Self Hosted Amazon S3 Cloud HTML5 MP3 Player for WordPress just in $24

You will need an amazon account to use this.

AWS access info

Add your amazon information amazon key and amazon secret key. Then just add the bucket to your account add folders.

Make sure you have public permission for all your music in your S3 buckets and folders.

Shortcode for Page or Post

[html5aws3mp3 player=”horizontal” bucket=”BUCKET” endpoint=”BUCKET-ENDPINT” folder=”FOLDER/”]

Plugin Page

Amazon S3 Error Handling

AWS CloudFront with PHP

Create sub buckets on amazon s3

Amazon S3 Cloud HTML5 MP3 Player is not associated in any way to

Amazon S3 Error Handling

Amazon S3 PHP Class A standalone Amazon S3 (REST) client for PHP 5.2.x using CURL that does not require PEAR.

AWS Management Console Home
AWS Management Console Home

AMAZON S3 (Scalable Storage in the Cloud) PHP CLASS

AWS access info
AWS access info

// AWS access info
if (!defined(‘awsAccessKey’)) define(‘awsAccessKey’, ‘CHANGE-KEY’);
if (!defined(‘awsSecretKey’)) define(‘awsSecretKey’, ‘CHANGE-KEY’);

OO method (e,g; $s3->getObject(…)):
$s3 = new S3(awsAccessKey, awsSecretKey);

Statically (e,g; S3::getObject(…)):
S3::setAuth(awsAccessKey, awsSecretKey);

Warning: S3::getBucket(): [PermanentRedirect] The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

We need to End Point for our S3 Buckets by default it’s

$s3 = new S3(awsAccessKey, awsSecretKey);

S3 Management Console
S3 Management Console

Else we need to specify here…

S3 Management Console
S3 Management Console

$s3 = new S3(awsAccessKey, awsSecretKey, true, ‘‘);

Warning: S3::getBucket(): [60] SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

We need SSL enabled with CURL 😉

OpenSSL phpinfo()
OpenSSL phpinfo()
CURL With OpenSSL phpinfo()
CURL With OpenSSL phpinfo()

For class documentation see:

Recover MySQL root Password

1. Stop the MySQL server.

# /etc/init.d/mysql stop

2. Start the MySQL server process with the –skip-grant-tables option so that it will not prompt for password.

# mysqld_safe –skip-grant-tables &

3. Connect to mysql server as the root.

# mysql -u root

mysql password
mysql password

Welcome to the MySQL monitor….
Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

4. Setup new mysql root account password i.e. reset mysql password.

mysql> use mysql;
mysql> update user set password=PASSWORD(“NEW-PASSWORD”) where User=’root’;
mysql> flush privileges;
mysql> quit

5. Exit and restart the MySQL server.

# /etc/init.d/mysql stop

6. Start MySQL server.

# /etc/init.d/mysql start
# mysql -u root -p