How to Develop Mpesa Integration to Website Using Safaricom C2B API


In this guide, you are going to learn how to develop Mpesa integration to website. Mpesa is one of the most popular mobile money transfer services in the world.

The innovative product is offered by Safaricom – Kenya’s leading telecommunication company with the strongest and widest network coverage.

With Mpesa, anyone can send money to you in Kenya using their Safaricom sim card and a mobile phone that supports a Sim Tool Kit(STK).

Safaricom has a ‘Lipa na Mpesa’ service specifically tailored for businesses that want to collect payments through the Mpesa payment gateway for Till and Paybill numbers(short codes).

Lipa na Mpesa offers a lot of convenience to customers and businesses. Text notifications are sent to merchants’ nominated mobile numbers when customers make payments to the business’s short code that is issued for free by Safaricom.

Apart from the SMS notifications, it is possible to develop Mpesa integration to website. This is a more effective way of pushing Mpesa transactions details to a website’s database automatically.

The transaction can then be processed further to update a website work-flow or business logic. The same analogy is used by banks in Kenya to credit customers’ Mpesa transactions to their respective accounts.

Developers can integrate with M-Pesa payment gateway by following the steps below.


  • A domain name for your business (e.g. You will get this free of charge if you purchase hosting space from Bluehost otherwise, you will have to part with $15/year
  • A web hosting space. I recommend a fast hosting provider like Bluehost to avoid timeouts when your API endpoints are called by Safaricom servers.

  • Apache or any other web server that supports PHP. This is installed by default if you purchase a host from Bluehost.
  • MySQL database – free from Bluehost.
  • PhpMyadmin to administer your database.
  • An FTP username with privileges to upload files to a web server.

Step 1: Create an account at Safaricom Developer Portal

Mpesa maintains a central developer portal at Just click the link above to create your account.

You will need to enter the following details. Please make sure the details are accurate.

  • First Name *
  • Last Name *
  • Account Type *
  • Username *
  • E-mail address *
  • Company Name
  • Country *
  • Mobile Number *

Step 2: Creating a C2B API and Generating a Consumer Key and a Consumer Secret

Once your account is approved, log in to the Mpesa developer portal by entering your username and password.

Click the “My APPs” link at the top left to create your first app, and then click on the “Add a new APP” button on your right.

Since you are creating Mpesa integration to website using c2b API, check the box that reads, “Mpesa sandbox for b2b, b2c and c2b apis” . Then assign your app any name e.g. MyWebsite Api

Then, click on the “Create APP” button.

Once your app is created, you need to click it under the heading, “These are your apps! Explore them!

At the bottom left, you will see your consumer key and consumer secret. Just copy-paste those details somewhere on your computer – we will need them later.

Step 3: Creating a Security Token to Safeguard Against Fake Transactions

Using M-Pesa payment gateway is a good way to receive payments on your website. However, it can become a target of hackers. To safeguard against this, you need to come up with a strong password that has a mix of letters, numbers, and special characters. e.g.


The password will be used as an authorization mechanism to secure your website’s call back URLs that Safaricom API will notify once you receive a payment on your Mpesa Till or Paybill number.

Step 4: Retrieve a Test Short-code

The Safaricom developer portal allows you to generate a short code that you can use to test your integration of Mpesa to your website before moving to production.

While logged in on the Mpesa developer website, open the link below to get a  test short code (e.g. 600413).

Copy the 6 digit shortcode 1 number and keep it alongside the consumer key and consumer secret that you generate earlier.

Step 4: Creating a Database Table to Store Mpesa Transactions

Integrating Mpesa on your website requires you to have a  database for storing transactions. You need to create a database and a table. You can use PHPMyAdmin to do this.

Your table schema should look like this. Let’s give this table a name like mpesa_payments

Auto - Auto number
TransactionType Varchar 40
TransID  Varchar 40
TransTime Varchar 40
TransAmount double
BusinessShortCode Varchar 15
BillRefNumber Varchar 40
InvoiceNumber Varchar 40
ThirdPartyTransID Varchar 40
MSISDN Varchar 20
FirstName Varchar 60
MiddleName Varchar 60
LastName Varchar 60
OrgAccountBalance Double

The length of the variable characters used above can be optimized and we have just used an arbitrary length to make sure the transactions will not fail.

Step 5:  Creating a Folder on your Website to Store Validation and Confirmation URLs

Next, we need to create a folder for holding Mpesa website API call back URL’s. When a customer makes payment to your till or Paybill number, Mpesa will first send the transaction details on your validation URL.

You should do your business logic to validate the transactions. For instance, you can check the amount or the account number and reject the transaction.

Create a folder on your website root. Assuming your website is, you can create a folder like However, using a random name is more secure e.g

Step 6:  Creating a C2B validation Callback URL  

Next, you need to upload a PHP validation file to that folder. You can use notepad to create the file and give it a name like “validation.php

So your full validation URL will read like this

Then, you need to copy-paste the following text on that file.



if (!isset($_GET["token"]))
echo "Technical error";

if ($_GET["token"]!='yourPU_RstrongPasswordSample$')
echo "Invalid authorization";

here you need to parse the json format 
and do your business logic e.g. 
you can use the Bill Reference number 
or mobile phone of a customer 
to search for a matching record on your database. 

Reject an Mpesa transaction 
by replying with the below code 

echo '{"ResultCode":1, "ResultDesc":"Failed", "ThirdPartyTransID": 0}'; 

Accept an Mpesa transaction 
by replying with the below code 

echo '{"ResultCode":0, "ResultDesc":"Success", "ThirdPartyTransID": 0}';

As you can see, you can either reject or accept the transaction by replying with the appropriate response.

Remember to change the token variable with the password that you created above.

Step 7:  Creating a C2B Confirmation Callback URL on Your Website

Create another file and give it a name like “confirmation.php

Your full confirmation URL will read like this

The confirmation URL will be called back by Safaricom when a customer transaction is finalized on their side. Therefore, we need to strip the JSON input from the Mpesa API and save the transaction details on our database that we created above.

Just copy-paste the below content on the confirmation.php file and upload it on your website. You can either do this using Filezilla or the file manager that ships with Cpanel especially if you are using Bluehost

Remember to replace the token variable with the password that you chose above. You also need to supply your Mysql hostname(server name), username, password and database name in the appropriate fields.



if (!isset($_GET["token"]))
echo "Technical error";

if ($_GET["token"]!='yourPU_RstrongPasswordSample$')
echo "Invalid authorization";

if (!$request=file_get_contents('php://input'))

echo "Invalid input";

$con = mysqli_connect($servername, $username, $password, $dbname);

if (!$con) 
die("Connection failed: " . mysqli_connect_error());

//Put the json string that we received from Safaricom to an array
$array = json_decode($request, true);
$transactiontype= mysqli_real_escape_string($con,$array['TransactionType']); 
$transtime= mysqli_real_escape_string($con,$array['TransTime']); 
$transamount= mysqli_real_escape_string($con,$array['TransAmount']); 
$businessshortcode=  mysqli_real_escape_string($con,$array['BusinessShortCode']); 
$billrefno=  mysqli_real_escape_string($con,$array['BillRefNumber']); 
$invoiceno=  mysqli_real_escape_string($con,$array['InvoiceNumber']); 
$msisdn=  mysqli_real_escape_string($con,$array['MSISDN']); 
$orgaccountbalance=   mysqli_real_escape_string($con,$array['OrgAccountBalance']); 

$sql="INSERT INTO mpesa_payments

if (!mysqli_query($con,$sql)) 
echo mysqli_error($con); 
echo '{"ResultCode":0,"ResultDesc":"Confirmation received successfully"}';

Step 8:  Registering Validation and Confirmation Callback URLs on Safaricom API

Finally, we need to register the validation and confirmation URLs on the M-Pesa payment gateway. This will enable Safaricom to call our URL’s when a transaction occurs on their side.

To do this, we need to create a third file and upload it to our website. You can call this file register.php.

So your full register.php URL will read like this

To register our validation and confirmation URL’s, we will use curl and PHP. Just copy-paste the text below on your register.php file and replace your shortcode, consumer key and consumer secret.

$consumerkey    ="replacewithyourconsumerkey";
$consumersecret ="replacewithyourconsumersecret";
/* testing environment, comment the below two lines if on production */
$registerurl = '';
/* production un-comment the below two lines if you are in production */
//$registerurl = '';
$credentials= base64_encode($consumerkey.':'.$consumersecret);
$username=$consumerkey ;
  // Request headers
  $headers = array(  
    'Content-Type: application/json; charset=utf-8'
  // Request
  $ch = curl_init($authenticationurl);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  //curl_setopt($ch, CURLOPT_HEADER, TRUE); // Includes the header in the output
  curl_setopt($ch, CURLOPT_HEADER, FALSE); // excludes the header in the output
  curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password); // HTTP Basic Authentication
  $result = curl_exec($ch);  
  $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
$result = json_decode($result);

//Register urls
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $registerurl);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.$access_token)); 
$curl_post_data = array(
  //Fill in the request parameters with valid values
  'ShortCode' => $shortcode,
  'ResponseType' => 'Cancelled',
  'ConfirmationURL' => $confirmationurl,
  'ValidationURL' => $validationurl
$data_string = json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
$curl_response = curl_exec($curl);
echo $curl_response;

However, you need to append the password that you chose above on your validation and confirmation URL’s using a token variable when registering the URLs.

So your validation and confirmation urls will read like this on the register.php file.

Validation URL$

Confirmation URL$

Once the file is ready, upload it to your website. You will then need to open the file with your web browser to register the URLs.

So on your web browser,  visit and your URLs will be registered automatically with the Mpesa API.

Step 9: Testing the Validation and Confirmation URLs Configurations

You can test the configurations of your validation and confirmation URLs using our Mpesa API URLs simulator:

This tool mimics what the Mpesa server does when a customer makes a transaction to your Paybill or Till number.

Once your validation and confirmation URLs are all set as discussed above, use our tool to send sample transactions to your website and see whether  Mpesa API works as expected.

Again, you can visit the tool from this link:

The tool looks like this:

Step 10:  Moving Mpesa API to Production

If you are able to complete the above steps and you got a success message during url registration. You can now move to production. On the Safaricom developer portal, click on the, “Go Live” link at the portal, you will be taken through a series of steps to prove ownership of your Paybill or Till number.

You will also need to download an Excel test case document, look for the c2b worksheet name at the bottom.

On the worksheet, create a new column with the name Actual Results and enter the word ‘okay’ or ‘success’ all the way from top to bottom. This signifies that you were able to run all Mpesa API test cases on your C2B API on the sandbox environment.

Mpesa API testcases.xlsx
Mpesa API test cases

Once everything is finalized, your app will be moved to production and you will get a new set of consumer key and consumer secret. Then, you will need to re-register URLs with your live Paybill or Till number plus the new set of credentials.

From this point forward, all transactions will be routed to your website database and you can do your business logic for further processing.

Pro Tip : Validation on your shortcode is not enabled by default. 

If you want validation for your Paybill or Till number, kindly write to and ask them to activate the same.

Sample Email:


Kindly enable external validation for our Paybill/Till number 111111. Our organization name is Sample Company. 

We would like to validate all Mpesa transactions before they are completed.



Remember to replace 111111 with your Mpesa Paybill/Till number and Sample Company with the real name associated with your Paybill or Till number


You can use this Mpesa API documentation to develop a customer to business API for your website. Remember, you can always refer to the Mpesa developer portal tutorials in case you run into a problem.

However, if you have followed the above Mpesa integration for website tutorial step by step, your c2b API will work without any hiccups.

Remember to check out our Mpesa C2B Simulator tool for simplified testing.

You might also like:

Mpesa B2C(Business to Customer) API


5 Tips to Secure a Linux Server Running Ubuntu 16.04

Linux is considered to be the most secure Operating System(OS). The open-source OS was built with unrivaled security in mind. Security experts from different Linux distributions react very fast to fix discovered threats and vulnerabilities.

Unlike Windows, Linux was built as a multi-user system from the beginning. Security best practices were followed since its innovation to segregate user files. Most applications run very far from the Kernel that controls the server.

However, no system is 100% secure. If you are using a Linux distribution such as Ubuntu 16.04, you need to follow the industry’s best practices to keep your system up to date and tighten your server’s security.

Here is a Linux server security checklist that you can use on your Ubuntu 16.04 virtual private server to protect your system if you are wondering how to secure your Linux server.


  • A Virtual Private server running Ubuntu 16.04 .

Tip 1: Update your System Frequently

Hackers take advantage of non-patched operating systems. To avoid becoming a victim; update your Linux system frequently using the command below.

sudo apt update && sudo apt upgrade

Tip 2: Create a Non-root User with sudo Privileges

Login on your Ubuntu server with super-user privileges can cause a lot of harm to your VPS server. It is always recommended to login to a system with limited privileges and only elevate the privileges when a task requires administrative rights.

To create a non-root user with sudo privileges, type the command below on your terminal. Replace the example_user with your preferred username

# adduser example_user

You will be prompted to enter the full details of the user including a password.

Next, you need to add the newly created user to the sudo group. Replace the example_user with your preferred username

# adduser example_user sudo

Tip 3: Create an Authentication Key Pair

Due to increased modern computing power, malicious attackers with unlimited access to your servers SSH port may try to brute-force your password to gain access to your system.

Using a public/private key pair for logging on your system is one of the best Linux server hardening tricks.

You can simply create the key pair using a tool like Puttygen. Then, upload the public key on your server and save the private key on your local computer.

You will use your private key every time you want to connect to your server. You can add another layer of security by securing your private key with a passphrase.

So, even if your private key ends in the wrong hands, a malicious user won’t be in a position to use your private key without the passphrase.

To copy a public key on your server,  log in with the user that you want to create the key pair for then type the command below:

mkdir ~/.ssh; nano ~/.ssh/authorized_keys

Then, copy the public key that you created from Putty key generator directly on the text editor

Press CTRL + X then Y and Enter to save the changes

Another Linux security best practices is to change the permission of the authorized key directory and file to make sure other users on the system cannot see the public key.


sudo chmod 700 -R ~/.ssh && chmod 600 ~/.ssh/authorized_keys

Tip 4: Disable SSH Password Authentication

Once you are able to log in on your Linux server with the private/public key pair, you need to disable password login.

To do this, you need to edit the SSH configuration file using nano text editor. Type the command below:

sudo nano /etc/ssh/sshd_config

Then, look for the line PasswordAuthentication and change to no

PasswordAuthentication no

Tip 5: Disallow root Login Over SSH

Even with the private/public key pair, log in on your system over SSH as the root does not go well with Linux server security best practices. To disable this, you need to edit the SSH configuration file using nano text editor.

Type the command below:

sudo nano /etc/ssh/sshd_config

Then, look for the PermitRootLogin directive and change it to no.

PermitRootLogin no

Restart the SSH daemon for the changes to take effect by typing the command below:

sudo service ssh restart

Tip 6: Install Uncomplicated Firewall (UFW) 

Linux server security best practices recommend UFW. It is installed by default in a fresh Ubuntu 16.04 installation but you can install it by running the command below if it was uninstalled.

sudo apt-get install ufw

By default, the general UFW rule is to deny all incoming traffic and allow all outgoing traffic. With the default settings, your virtual private server will run smoothly but it can’t allow external communications.

You need to allow the necessary ports otherwise you might completely lock yourself from your system.

Enabling SSH or Secure FTP server for Linux on UFW

Since logging on the server via SSH is essential, we need to allow port 22 by typing the command below. You might change the port if you had configured a different port for SSH.

The SSH port is the same if you want to log in on your system using a secure FTP server for Linux using a tool like Filezilla.

sudo ufw allow ssh


sudo ufw allow 22

Next, we need to allow port 80 and port 443 because they are specifically used for internet traffic. If you don’t want users to access your server on the un-encrypted channel(HTTP), you may skip the step of allowing port 80 and only allow port 443 for https traffic only.

Enable HTTP traffic on UFW

sudo ufw allow 80


sudo ufw allow 80

Enable HTTPs Traffic on UFW

sudo ufw allow 443


sudo ufw allow https

Enabling UFW

Once you have made the necessary changes, you can enable the UFW by typing the command below

sudo ufw enable

Disable UFW

You can also disable UFW by typing the command below

sudo ufw disable

Checking the UFW rules

You can always check the enabled UFW rules by typing the command below:

sudo ufw status verbose

Deleting  UFW rules

To delete a UFW rule, you need to check its number by running the command

sudo ufw status numbered

Then, once you get the number, just run the command below e.g. to delete rule number 2

sudo ufw delete 2

Resetting UFW

You can always run the command below to reset UFW and start all over again

sudo ufw reset

Top Linux Commands With Examples

Here are the basic Linux commands that works on any distribution including Ubuntu 16.04. Only use the commands if you are sure about what you are doing. Remember,  a single command like rm can completely wipe your server files if used incorrectly.

No Command  Description
1 cat displays the content of a file
2 cd Change directory

e.g. cd /var

3 chmod change permissions of a file
4 chown change the ownership of a file or directory
5 cp copy  a file

e.g. cp /var/test1.text /var/test2.text

6 cp -a copy a directory
7 df -h reports the amount of available disk space
8 du –h shows the disk usage in a specific directory

e.g du -h /var

9 find locates a file or a directory
10 history display all  previous commands typed in terminal
11 ifconfig see the TCP/IP settings of the system
12 ls list directory contents
13 mkdir Short form for make directory. Used create directory

e.g. mkdir samplefolder

14 mv move a file
15 pwd print working directory
16 reboot restarts the system
17 rm removes a file
18 rm -f removes a directory without giving any warning
19 shutdown –h shuts the system down
20 tar compress/decompress files
21 uptime see how long the system has been running
22 date display the current date and time

How to Install and Secure phpMyadmin on Ubuntu 16.04

According to a report by Gartner,  open source databases are quickly consuming the market share of commercial relational database management systems (DBMSs).

MySQL is one of the most preferred databases and has matured enough over the years to replace commercial options such as Oracle and Ms SQL. Any application development team can now permanently consider MySQL as their standard choice for holding their production environment data.

However, many system users feel uncomfortable when dealing with MySQL over the command prompt which can be quite challenging.  The best option of managing and interacting with your MySQL database is phpMyadmin.

Let’s see how you can install phpMyadmin on Ubuntu 16.04 VPS server


Step 1: Update your system and install phpMyadmin from the Ubuntu repository

PhpMyadmin is maintained on the Ubuntu repository, so we are going to use apt-get to pull the package by typing the commands below:

$sudo apt update && sudo apt upgrade

$sudo apt-get install phpmyadmin

Confirm the installation by pressing Y and Enter on the prompt that appears

Step 2: Select your web server

Once the files are installed on the system, you will see an option to configure phpMyadmin. Select [ ] apache as the web server that should be automatically configured to run phpMyadmin.

Step 3:  Configure database for phpMyadmin

On the next screen, you will see an option to configure database for phpMyadmin dbconfig-common, just select Yes and hit Enter to continue.

Step 4: Provide password for phpMyadmin

By default, phpMyadmin requires a database and a password that should be registered with the MySQL server. You should enter a strong password once you get a prompt to provide it and press Enter to continue. Don’t leave it blank. Remember to confirm the password on the prompt that follows.

Step 5: Creating symbolic links

The phpMyadmin Installation process should add a symbolic link to the /etc/apache2/conf-enabled/ directory by default. Sometimes that does not happen. When you try to access PhpMyadmin from the web browser, you will get an error, “Not Found. The requested URL /phpMyadmin was not found on this server.

To create the symbolic link manually, enter the following commands :

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf

sudo a2enconf phpmyadmin.conf 

sudo service apache2 reload

Step 6: Confirm the installation

Once the installation is completed, you can check whether PhpMyadmin is working by visiting the link below from your browser. Remember to replace and with your domain name or IP address respectively. 

If the installation was successful, you will see the phpMyadmin login page.  You will need to enter your MySQL root password that you defined when Installing MySQL to access your databases.

If something went wrong during the configuration, you can run the command below to re-configure phpMyadmin

sudo dpkg-reconfigure phpmyadmin


Finally, you have configured phpMyadmin to work with MySQL on your Ubuntu 16.04 VPS server. Remember, you can create databases, tables, users, insert, update and delete records on the phpMyadmin interface just like you would normally do on the MySQL command prompt.

For security reasons, don’t configure your websites or applications to run with the MySQL root user. Just create a separate username and a password for each website to safeguard your databases.

How to Install and Secure MySQL on Ubuntu 16.04 VPS Server

MySQL is one of the most popular database systems that utilize Structured Query Language (SQL). The relational database is commonly used alongside Apache/LightSpeed/Ngnix web servers and PHP/Perl/Python scripting languages.

Due to its stability, MySQL is used by many developers in production. Popular uses include WordPress, Joomla and Drupal content management systems. MySql is also used in major websites including Facebook, Twitter, YouTube and Google.

The database management system is very secure, scalable and performs well especially in an environment that demands the use of transactions. MySql’s complete workflow and reduced total cost of ownership gives developers the flexibility of using it.

MySQL works pretty well in an Ubuntu 16.04 Virtual Private Server and here is how to install it.


  • An Ubuntu 16.04 VPS server from Digital OceanVultr or Linode.
  • A command line tool like putty.
  • A non-root username with sudo rights.

Step 1: Downloading MySQL from the Ubuntu Package Repository

MySQL is maintained in the Ubuntu central repository and we can pull it using the apt-get command. But before we do this, we need to make sure that our Ubuntu 16.04 server is up to date.

Run the command below to update your Ubuntu server

sudo apt-get update

Then install MySQL server by running this command.

sudo apt-get install mysql-server

Press Y then Enter when you are promoted to install the package.

Step 2: Setting the MySQL Server root Password

MySQL server has a default user called root and should not be confused with the root of your Linux system. Once you complete the MySQL installation, you will be requested to supply a password for the root user.

Kindly use a strong password for security purposes. A mix of upper and lower case characters combined with numbers and special characters form a hard-to-crack password. Press Enter after entering the password and confirm the same on the next screen

Step 3: Securing the MySQL Server

The default MySql installation is not secure because it contains anonymous users and a test database. So we need to harden the installation to avoid somebody from login on the system with the default settings.

Luckily, we can run a command that will make things easier for us. Just type the following on your command line tool:

sudo mysql_secure_installation

The command will run and you will be prompted to enter the MySQL root password that you created in Step 2 above.

Password Validation Plug-in

MySql secure installation will prompt you to setup a Validate Password Plug-in which is used for testing MySQL passwords to improve security.

The command will read as follows

Would you like to setup VALIDATE PASSWORD plugin?

Press Y and Enter to enable the Plug-in

The Validation Plug-in has three levels of password validation policy

LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file

You will get a prompt to choose your desired policy which reads as follows

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:

Just enter 2 and press Enter. This will make sure that passwords created for any MySQL database user will contain a mix of numeric, mixed case and special characters.

Changing Password for the root User

Next, you will get a prompt to change the password for the MySQL root user.

The prompt will read as follows:

Change the password for root ? ((Press y|Y for Yes, any other key for No) :

Since we chose a strong password while installing MySQL in the above steps, we are not going to change the password. So just press N and Enter to proceed.

Removing Anonymous Users

Leaving any anonymous users on your MySQL database is very dangerous. You will get a prompt to remove the user.

The prompt will read as the below text:

Remove anonymous users? (Press y|Y for Yes, any other key for No) :

Press Y and then Enter to remove the user

Disallowing Remote root Login

MySQL remote root login leaves an open door for hackers who can recursively connect from any IP address to your MySQL server and probably brute-force your password.

To disable this, you will get a prompt which reads:

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y

Press Y and then Enter to disable root login remotely

Deleting the MySQL default test Database

Fresh MySQL installation comes with a test database named ‘test’ that can be used by anyone. This is intended for testing and should be removed in a production environment.

You will get a prompt to remove the database which reads as follows:

Remove test database and access to it? (Press y|Y for Yes, any other key for No) :

Press Y and then Enter to remove the database

Reloading MySQL Server Privileges

The changes we have made so far have not yet been committed to the system and MySQL privileges need to be reloaded.

The prompt for refreshing the settings will read:

Reload privilege tables now? (Press y|Y for Yes, any other key for No) :

Press Y and then Enter for the changes to be effected. Finally, you will see a success message.


All done!

Step 4: Disabling Strict SQL Mode in MySQL 5.7

The default MySQL strict mode can bring problems when you try to insert data in a table. If a field is null and there is no default value defined, the transaction will fail.

Let’s create a new MySQL configuration file and make the changes using a nano text editor.

sudo nano /etc/mysql/conf.d/disable_strict_mode.cnf

Once the text editor opens, enter the following text


Press CTRL + X then Y and Enter to save the changes

You need to restart the MySQL server for the changes to be effected by entering the command below on your terminal.

sudo service mysql restart

Step 5: Checking the Status of MySQL server

The MySQL server installation on our Ubuntu 16.04 VPS server is complete but we can test whether everything is working by running the below command.

sudo systemctl status mysql.service

If there were no hiccups with the MySQL installation, you should see the following status text:


That is all it takes to Install MySQL server on your Ubuntu VPS. From this point, you can create MySQL databases, tables and users using the command line. However, if you want a better tool to manage your MySQL database from a web browser, you should consider installing phpMyadmin. See my guide for installing phpMyadmin on Ubuntu server 16.04.

How to Install PHP 7 on Ubuntu 16.04 Running Apache Web Server

PHP (Hypertext Preprocessor) is one of the most preferred and powerful general purpose programming language. The open source scripting software runs millions of dynamic websites including CMS (Content Management Systems) like WordPress and OpenCart.

PHP popularity comes from the community support that builds free production frameworks such as Laravel . This has made the life of many PHP web developers extremely easy.

PHP still breaths despite a tough war from competitors such as, Python, Node Js and Angular Js.

Nevertheless, PHP is efficient, free and a faster scripting language that works well with most Linux distributions.

You can install PHP on your Linux 16.04 VPS server by following this guide.


 Step 1: Using apt system to install PHP

PHP is maintained in the Ubuntu central installation repository so we can pull it from there using the apt-get command.

Before you do this, please update your system by typing.

sudo apt-get update

Then Run the following commands to install PHP

sudo apt-get install php libapache2-mod-php

Press Y and Enter when the installation confirmation prompt appears.

The libapache2-mod-php downloads the required module for an Apache server.

Step 2: Modify Apache default Index files

By default, Apache prioritizes index.html, index.cgi and when a user requests a page from the root of a website or directory. To override this setting, we need to edit Apache dir.config file.

Type the command below to open the Apache directory configuration file and edit it using nano.

sudo nano /etc/apache2/mods-enabled/dir.conf

Once the file opens, moves index.php just after the text DirectoryIndex to give it precedence over other default index files. At last, your dir.conf file will then read as follows

<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.xhtml index.htm

Then, press CTR + X then Y and Enter when you are done to save the changes to the file

Step 3: Install basic PHP Modules

You probably want run a website or an application on your Ubuntu 16.04 VPS after installing Apache. Therefore, we need to install basic PHP modules to ensure your sites work without any problem.

To do this, type the command below:

$ sudo apt-get install libapache2-mod-php php-cli php-common php-mbstring php-gd php-intl php-xml php-mysql php-zip php-curl php-xmlrpc


The command above will install all the necessary PHP modules that you need to run your websites.

Step 4:  Configuring PHP

By default Php7 configuration file path is /etc/php/7.0/apache2/php.ini after the installation. We need to make some changes to that file so that our websites or applications will run without a problem.

To do this, type the command below to open PHP configuration file on the nano text editor:

sudo nano /etc/php/7.0/apache2/php.ini

You need to find the upload_max_filesize = 2M  AND post_max_size= 8M  settings on the php.ini file and change them to read as follows:

upload_max_filesize = 16M
post_max_size = 16M

You can increase the values according to your needs if you anticipate file uploads of more than 16MB

Then, press CTR + X then Y and Enter when you are done to save the changes to the php.ini file. 

Step 5: Test PHP

Finally, we can now test PHP by creating test file on the var/www/html/ folder. If you are running multiple websites using virtual hosts, you need to match the document root with the default public html folder that you created for your website(s).

Type the command below to create the info.php file

sudo nano /var/www/html/info.php

Then, enter the text below.




Press CTRL + X then Y and Enter when finished to make changes to the file.

Step 6: Restarting Apache

We need to restart Apache for all the changes we have made to be effected. We can do this by typing the command below.

sudo systemctl restart apache2

You can now visit the info.php file on your website using your domain name or IP address to see if PHP is working. You can do this by typing the below text on a web browser. Remember to replace and with your domain name or VPS server IP address respectively.


If everything was set correctly, you will see a page that looks like this.


That’s it when it comes to installing PHP 7 on Ubuntu 16.04 server running an Apache web server. Remember, you can now create additional PHP files or probably run a content management system like WordPress and it should work pretty well when PHP is installed.