Few months back I wrote an article about developing RESTful services using PHP, Slim and MySQL. But the services are not accessible to public as they are limited to localhost. In this article we are going to learn how to host the services on a realtime server, so that, they can be accessible from anywhere.

I tried hosting the services on free hosting spaces (like 000webhost.com), but because of limitations (like not supporting PUT, DELETE methods and mysqlnd) I couldn’t able to run the services. So I decided to move to a VPS hosting like Digitalocean to host the services. Digitalocean provides very high hardware configuration in cheaper prices (which is almost equal to shared hosting).

digitalocean deploying android php mysql restful services

Prerequisite

As this tutorial is continuation of below two articles, make sure you learn them well to know how to develop RESTful services for your android app.

How to create REST API for Android app using PHP, Slim and MySQL – Day 1/2

How to create REST API for Android app using PHP, Slim and MySQL – Day 2/2

Download the code from this link as we are going to see hosting this project into digitalocean.

1. Buying & Setting Up DigitalOcean (Get $10 free credit)

DigitalOcean offers various pricing plans ranging from $5/m to $640/m. For an entry level app, $5/m plan (which comes with 512MB Memory, 1 Core Processor, 20GB SSD & 1TB Transfer) is powerful enough to get started. If you think this configuration is not enough for your app, you can always upgrade to other plans.

Register your self with DigitalOcean by creating an account. Use this link to get $10 free credit in your account. In other words you don’t have to pay for the first two months (assuming you are choosing $5 plan).

Create a new account here. Give your email and password. You’ll receive the confirmation mail to your email account.

Activate the account by verifying the email sent to you.

Once the account is activated, you will be prompted to give your credit card details. Without giving the credit card details you can’t create the droplet. Don’t worry about giving the credit card information, there won’t be any money deducted from your card right away.

Check the below video to know the registration process.


2. Getting the Droplet Ready

Once you gave the credit card details, you will be allowed to create a droplet. Droplet is nothing but an instance of a server. Follow below steps to configure your droplet.

2.1 Click on Create Droplet on left sidebar or click this link to go to the page directly.

2.2 Give your droplet a name

2.3 Select the size. I selected $5/m plan.

2.4 Select the region. I selected New York.

2.5 Select the distribution image. I selected Ubuntu 14.04×64

2.6 Under applications tab, select LAMP on 14.04. This will install Apache, MySQL and PHP on creation of the droplet.

2.7 Click on Create Droplet to complete.

It will take few minutes to create the droplet. Once the droplet is created, your new server instance details (ip, username and password) will be mailed to your email id.

If you visit the ip address in browser, you can see apache welcome page. Now follow below steps to complete the droplet setup.

2.8 Logging into droplet via SSH
You can login into your server via ssh. Mac users can directly connect using terminal tool. But windows users needs download ssh client like Putty to login. Download Putty and execute below commands to login into your server.

In putty, give your server ip address, port number as 22 and click open. You will be asked to give your username and password. Use the credentials those sent to your email.

Mac users, run the below command directly in terminal.

ssh root@YOUR_IP_ADDRESS

2.9 Resetting Root Password
When you are logging in for the first time, you will be asked to change your password. Give your old password and new password to change.

3.0 Resetting MySQL Password
As MySQL is installed by selecting the LAMP app while configuring the droplet, we are not sure about the mysql password. You can see the current MySQL password in the console when you are logging in. This password is randomly generated and kept. In order to change the MySQL password, follow below steps.

sudo service mysql stop
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
mysql -u root
FLUSH PRIVILEGES;

Replace ‘newpassword’ with your new mysql password.

SET PASSWORD FOR root@'localhost' = PASSWORD('newpassword');
FLUSH PRIVILEGES;
exit

You can find complete article about resetting MySQL password here.

3.1 Enabling mod rewrite
Apache rewrite module helps in writing the urls to another url. This is useful for us to shorting the Slim urls. So enable it by running the below command.

sudo a2enmod rewrite

3.2 Enabling mysqlnd
MySQL native driver is needed to run the mysqli functions. So install mysqlnd by executing the below commands.

sudo apt-get update
sudo apt-get install php5-mysqlnd

Now restart the apache to take the changes effected.

sudo service apache2 restart

Checkout the below video that will take you through completing the droplet setup.


3. Installing phpmyadmin

You can create database using the mysql command line tool or using the phpmyadmin. I prefer using phpmyadmin as it is lot more easier than the command line tool. Follow the below steps to install phpmyadmin.

sudo apt-get install phpmyadmin apache2-utils

While installing you need do below steps.

Select Apache2 by pressing the SPACE key. When selected, you should see a start (*) indicating Apache2 is selected.

Choose YES whenever it prompts to configure the database for phpmyadmin

Enter MySQL password when prompted

Enter phpmyadmin password that you want to login with

Now you can test your phpmyadmin by visiting http://_YOUR_IP_ADRESS_/phpmyadmin (Replace _YOUR_IP_ADRESS_ with your actual server ip)

The below video will take you through installation of phpmyadmin.


4. Creating the Database

Goto your phpmyadmin and execute the below SQL to create the required database and tables. Once executed, you can see the newly created database on the left panel.

CREATE DATABASE task_manager;
 
USE task_manager;
 
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) DEFAULT NULL,
  `email` varchar(255) NOT NULL,
  `password_hash` text NOT NULL,
  `api_key` varchar(32) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '1',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
);
 
CREATE TABLE IF NOT EXISTS `tasks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `task` text NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
);
 
CREATE TABLE IF NOT EXISTS `user_tasks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `task_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  KEY `task_id` (`task_id`)
);
 
ALTER TABLE  `user_tasks` ADD FOREIGN KEY (  `user_id` ) REFERENCES  `task_manager`.`users` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;
 
ALTER TABLE  `user_tasks` ADD FOREIGN KEY (  `task_id` ) REFERENCES  `task_manager`.`tasks` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;

The below video will show you creating database and tables.


5. Uploading your PHP Project

Now we’ll upload our project to the server. For this you need a FTP software like FileZilla. Download FileZilla and login to your server using the credentials as Host (your ip address), Username, Password and Port (give 22 as port number).

Once connected, goto the directory /var/www/html on the right panel and delete index.html and info.php. This is the root directory for all our php projects.

In your php task_manager project, goto include and change the credentials of MySQL in Config.php with your database username, password and database name.

Now upload the task_manager folder to html directory.

Goto /etc/apache2, open apache2.conf and change AllowOverride to All under <Directory /var/www/>. This step is very important to eliminate index.php from our api urls.

<Directory /var/www/>
	Options Indexes FollowSymLinks
	AllowOverride All
	Require all granted
</Directory>

The below video will show you how to upload your project using FileZilla.


6. Testing the API

Now we have everything in place, let’s test the API using Chrome Advanced REST client. Install the extension and test your url endpoints as shown in the below video.

URL Method Parameters Description
http://your_ip_address/task_manager/v1/register POST name, email, password User registration
http://your_ip_address/task_manager/v1/login POST email, password User login
http://your_ip_address/task_manager/v1/tasks POST task To create new task
http://your_ip_address/task_manager/v1/tasks GET Fetching all tasks
http://your_ip_address/task_manager/v1/tasks/:id GET Fetching single task
http://your_ip_address/task_manager/v1/tasks/:id PUT Updating single task
http://your_ip_address/task_manager/v1/tasks/:id DELETE task, status Deleting single task

7. Mapping the Server with a Real Domain URL (Godaddy)

You can buy the domain from whichever service you like. In this tutorial I used Godaddy.com to buy my domain url.

Goto godaddy.com and search for the domain you want to buy. If it is available, complete the checkout process.

Launch the Zone File Editor for your domain.

Click Add New Record. A popup will be shown to edit the record.

From the Record type list, select A(Host)

Enter host value as @ and points to value is ip address of the droplet and click on finish.

It will take sometime to get the changes reflected depending upon your service provider. After sometime, if you visit the domain, it should points to our droplet. Once mapped, you can change the ip address to your domain url in the REST API urls.

Check the below video to get clear understanding of mapping the domain with droplet.


Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
  • Renitto Jose

    this query is not related to this post. Can u please suggest some links , where i can download some Templates for login page .
    Something like this :- https://dribbble.com/shots/1451751-Sign-In-3/attachments/214758

    Thanks in advance 🙂

  • Guest

    Will try this over the weekend, thanks for the guide! 🙂

  • Scrobie Ballstein

    Thanks for this Ravi, you’re the man!

  • Man you’re Awesome!! many thanks!

    • Stark

      Hi there, I ran it in localhost, everything work well
      But when I ran it in http://my_id_address/task_manager/v1/register
      It not working. Please help me

      • yngcan

        Android Creating REST APIPHP Projecttask_managerv1index.php
        “authorization” should update to “authorization”. then it will work.

        • yngcan

          Authorization need change into authorization

  • Mohammad

    Man you’re Awesome!! many many thanks!

  • Aiman Baharum

    Coolest!

  • Alejandro G

    Thanx, it’s a amazing tutorial Ravi!

    • You are welcome 🙂

      • kartik

        Please Help !! I’m getting error in POST and PUT.

      • Trey Rosius

        Hi Ravi, i’m having difficulties figuring out how i can parse the authorization header in my android app.Please just tell me what to do or better still, suggest a link that illustrates it. i beg you.

        • Abhishek Rohilla

          use the function apache_request_headers() in php. and check for
          if (isset($headers[‘Authorization’]))
          Not sure why would you want to parse it in Android app. Android app is the one sending the request headers.

  • sreeshty raychoudhury

    awesome,

  • Kim Dotnet

    amazing tutorial like always ! 😀

  • Sandeep Reddy M

    Excellent tutorial Ravi. I have one question, After two months of Free account shall I remove from digitalocean, If I don’t want to pay money for that. Thanks in Advance

  • Trey Rosius

    @ravi8x:disqus, if i had 1/10000 of your skills, i won’t be on this planet.Your something else..For real..I’ve just completed my social Network APP based on REST..thanks to you.Now testing it.May the good Lord Bless you Mayne…keep’em comming

    • Thank Trey, I am glad my tutorial helped you a lot 🙂

      All the best

      • vishakha

        hello ravi plz help unable to run url register.need index.php with registration

  • Abhishek Rohilla

    This is a nice tutorial Ravi.

  • Alireza

    anyone know if this tutorial is going to continue to for client side source in android?

    • Rodrigo Vieira da Costa

      I need too!!! help!!

  • Rodrigo Vieira da Costa

    @ravi8x:disqus this tutorial is excelent, and I was wondering if you can help us create a sample android app using this api php and mysql slim, with CRUD. Thanks!

  • Abhay

    Awesome and Great Tuts Bro nobody on internet has putted them in simple and concise manner as you have done thanks for sharing this knowledge with us god bless you bro .
    #indian rocks 😀

  • Stark

    Everything worked well in localhost.
    But when I try to register it in
    http://my_ip_address/task_manager/v1/register.

    Use post and fill full information just like you.
    I got the error “500 internal server error”.
    Please tell me why ?

    • Indra

      Check your domain is pointed to your ip address

  • Jun Jun

    Awesome! It will be good to have tutorial on Cloudant 😀 https://cloudant.com

  • Andy

    Great Tutorial. Is there special configuration to deploy to IIS

  • will

    when or will you follow this with the android side of things? have the api running but I need to know how to handle it on the android side so I can get the data into the app?
    Great tutorial, very helpful!!

    • Once your REST API is ready, its just making an http call from android and get the response.

      • Stack Trace

        How? can you briefly explain here how to connect it with android in order to have a clue (Classes, Methods)?

        • Ken Choong

          use volley library to make the network call

      • arjun hegde

        How do I post request from android app??

  • Akie Kaz

    Hey Ravi, thanks alots about the tutorials, could you help me with this one?

    about SSL, im always using the JSONParser from your site, thanks alot for that that worked nicely.
    but, when i put the URL with ‘https://’ or link with Sub domain, its called error about SSL like :
    SSLHandshakeException: Received fatal alert: handshake_failure

    as i search on Google, it must adding some keytool, but i found also with not using keytool and using import about Ceritificates, but still not working for me, could you help me about the simple tutorials? many thanks for that!

  • Meshileya Israel

    thank you so much for this

  • Srikanth Y.

    Ravi, You rock bro..

  • Braja Pal

    Hi Ravi really u are the Sun … it works perfectly . i think u might have forgotten to put some file like header(‘content-type: application/json; charset=utf-8’);header(“access-control-allow-origin: *”) etc etc in ../v1/index.php in order to access in phone gap.i put these header it works in phone gap smoothly 🙂 thanks 4 ur hard-work …

  • Vishal Kumar

    Hi Ravi. Thanks for your nice tutorials. I have one query since long. I am developing an android quiz app with PHP/MySQL backend… i have hosted them on godaddy…i am using volley … but it seems to be slow enough…something throwing Unknown Host Exception… I have heard about Amazon SWS, Mango DB…. not sure why people prefer them…. Is there a way … I can continue with MySQL database with PHP APIs… but fast response. Any recommendation will be welcome.

    • Shared hosting will be always slow. Try to move on to a VPS. Digitalocean is an VPS server. Compared the AWS it is slower but good enough for a beginner app.

  • ranjithstar256

    Thank You sooo Much Ravi bro :))))))) You helped me a Lot in Learning Android! and am working as Android Trainer for the past one and half years and placed many of the students in a good company 🙂 credit goes to you also Ravi bro 🙂 feeling happy about it 🙂 and today by following this tutorial I have just build my website also 🙂

    Thanks a lot brother 🙂 Keep up the Good work 🙂 All is Well 🙂
    if have money, would have bought a Mercedes-Benz Car for you :p :p 😀 :))

    • Hi Ranjith, I am glad that me and my blog helped you a lot. You have also done a good job in helping lot of students for their carrier. You too keep the good work.

      By the way thanks for your Benz 😀

      • ranjithstar256

        Sure Ravi bro :))))) :p 😀 *THUMBS UP*

  • Vishal Kumar

    Hi Ravi… while installing phpmyadmin on digitalocean… i made a mistake… “Select Apache2 by pressing the SPACE key. When selected, you should see a start (*) indicating Apache2 is selected.”- I missed to select Apache and now …it’s not validating my password. How can I recover back… have no background in UNIX… plz help.

    I tried myself..but it says – unable to lock the administration directory (/var/lib/dpkg/) is another proc

  • stelios99

    Hello Ravi, can you make the same guide but instead of Php, use a Java back end framework ? This will be very helpful to me.

  • Harshit

    AWS tutorial please!!!!

    • Francis Ishmail

      Did you figure this out?

  • SADEGH ARFA

    Hello Ravi , Tnx for very excellent tutorial ^_^
    it’s work very well in localhost but on the host some of actions don’t response
    for example register and login working but getAllTasks not working for me and get me 500 error
    i checked every thing but .. 🙁

  • ritesh goel

    Hello ravi, can you please instruct us how to do it with AWS also?

  • Ashutosh Tripathi

    Hi, Ravi getting 500 internal server problem on postman…its not hitting the api

    • Ken Choong

      bro do u solve this??I also having the same problem

  • Rishna

    Hello can you explain how to connect the API to real android app and how it will work? The tutorial is nice and helpful, how do we hit the URLS from the app so that all the action can be done? It will be good to show example of how to link app to APIs.

  • rehan

    Can you give me any instructions as to what to do if I have a plesk based server? How to publush my api on there?

  • Prasanth

    Hi Ravi, I have website with complete database in mysql and php, where the users register and login and then they register for events. I wan to connect this existing database to the android app so that users can login though the app too. I have never worked in the backend side of android . Ps : I have created an Api for this registration already . Can you please provide me some information on how to do connect this database to my android app .

  • Imam Aly

    Hi ravi, i try hosting in other vps host service. when i inserting using post method to mysql database server, then i select using get. the query not update. need some minutes to update the last query from get method. but when i look on phpmyadmin the query already exists. what i need to do some configuration to fix them, or the problem from host service?
    P.S : There is no problem on localhost

  • Ken Choong

    Bro,1stly thanks for your hard work.But I face little problem,I done set up the server,set the database,but when I hit my url,it state not found.Can u give me some hint,why is this happen??

    • Ken Choong

      The requested URL task_manager/v1/login was not found on this server. is no problem in localhost..

    • Baronarama

      you should not be able to directly access the url like “URL/task_manager/v1/login”
      not even “URL/task_manager/v1” however you should be able to test it with Advanced REST client for chrome, check the video.
      You can’t access the direct url due to mod rewrite I think and that’s on purpose.

      • Ken Choong

        ya I test in Rest client..but it show me could not access to the server

  • Baronarama

    By following other tutorials as well, I came upon problem while testing. Seems to be working but not correctly.

    When I do the testing with https://www.hurl.it/ I get “500 Internal Server Error” and the error on apache is:
    “PHP Fatal error: Call to a member function bind_param() on a non-object in /var/www/html/android/include/DbHandler.php on line 43”

    When I try with chrome app, ARC, I get something different
    {
    “error”: true,
    “message”: “Email address is not valid”
    }
    And no matter how or which email I use I always get not valid.

    • Baronarama

      I went and reinstalled everything and now it works when I use the mentioned website.
      {
      “error”: false,
      “message”: “You are successfully registered”
      }

      But still when using Advanced REST Client I get email error.
      Anyway it is working and thank you for tutorial, what did I do wrong the first time, no idea.

      Why ARC doesn’t work? No idea, I guess the new update messed up something, my guess is that it sends @ as a character and not as a code %40 because ARC request looks like
      password=aaaa&email=email@gmail.com&name=Baro
      And from the website it looks like
      password=aaaa&email=email%40gmail.com&name=Baro

  • Ken Choong

    Ravi,I wanna ask,I get 500 internal server error for every url in my index.php.I already follow every single step in ur tutorial,for god’s sake,please give me 1 single guide for me to solve.please..thank you

    • Baronarama

      If you get 500 internal server error, check /var/log/apache2/error.log

      • Ken Choong

        Hi bro,1st thanks for reply..I just checked
        [:error] [pid 5347] [client 115.133.247.14:594 23] PHP Warning: require_once(../include/DbHandler.php): failed to open stream: No such file or directory in /var/www/html/task_manager/v1/index.php o n line 9

        it stated that it cant open DBhandler.php..this file I already upload to the server as well
        U know how to solve this??

        • Baronarama

          Check the folder structure if you have files in right folders/subfolders
          Also check the file names, they have to be correct, so if you copied the code you have to name the file correctly DbHandler.php in other tutorial it’s Db_Handler.php so be careful with that too.
          And the last thing if you copied the code check the name of the class that it’s correct so it should be “class DbHandler”
          Hope this helps 🙂

          • Ken Choong

            Thank you for pointing out.I solved! Good luck to you too

  • Ken Choong

    Ravi..I sincerely say Thank you very much.I have nothing more to say.

  • Joaquin Cardenas

    Im facing this problem “mysqli::__construct(): (HY000/2002): Connection refused”.
    Has anyone overpassed it?