There are a lot of ways through which you can build up a website. In this article, we’re going to teach you how to serv JSON Data from a PHP server.
For example, have you ever wondered how opening a browser opens a new world of fun-filled opportunities? Or better yet, have dreamt of building your own successful app or network, allowing you to go into your new business venture?
Throughout this tutorial, we’re going to access data in JSON format. We will start by deploying a SkySilk VPS server, installing LAMP stack into it and then using PHP as the backend language to access some data from the MySQL database, then serve our JSON data from a PHP Server!
Prerequisites
A basic knowledge of how to create new users and give them proper permissions.
Read more: Navigating Your Filesystem in the Linux Terminal
Deploy an Ubuntu Server
Step 1: Deploying a VPS server
For this tutorial, we’re going to deploy a server with Ubuntu on it. You can also deploy a CentOS server.
Step 2: Once deployed, launch the SSH terminal to manage the server and install the LAMP stack
Click on the “SSH CONSOLE”. A popup will open and ask you to login to your server as the root user. Type your server password to login.
Create a new sudo capable user.
When working with any Unix machine, it is recommended to run commands as a sub-user, and only to use root when necessary. This ensures that there are no file permission errors due to things being owned by the root user. Some softwares will even completely disallow the use of the root account for installation and will warn you as such when you attempt to run their installation commands as root.
adduser <username>
This will begin a series of prompts including password and profile information for the new user.
usermod -aG sudo <username> su <username>
Step 3: Afterwards, update and install Apache using Ubuntu’s package manager.
Let’s run below commands one after another.
sudo apt update sudo apt install apache2
We use sudo to grant root privileges. While installing the Apache web server, you’ll be asked about how much extra disk space it would take up and whether you want to continue or not. Press Y and hit ENTER to continue with the installation.
Since we are going to access the API via our browser only, we’ll have to make sure that the server IP is accessible using http (or https).
sudo ufw allow "Apache Full" sudo ufw allow ssh sudo ufw enable
It is very common for users to accidentally miss the step of allowing SSH connections to the machine before they enable UFW. If this happens, you will be locked out of your server via SSH and will need to use the VNC console from your SkySilk Dashboard to run the above commands.
You can now type in your server’s IP in the address bar of your browser and you’ll see the default Apache page when you access it.
Read more: 9 Free Windows Terminal Apps
Install MYSQL
In order to serve our data via REST API, we need to set up a database.
Step 4: We need to install MYSQL
MySQL is a relational database management system that uses SQL as its query language to do CRUD (Create, Read, Delete, Update) operations.
sudo apt install mysql-server<br>
Again the terminal will ask you for permission to install specific packages. Grant them access by pressing ‘Y’ and then ‘Enter’.
Note: If you are asked to restart some services, Click Yes and proceed with the installation.
Now to check whether or not MySQL has been installed correctly onto your server, just paste the below code. This will show you all the MySQL libraries that the server currently has.
dpkg --get-selections | grep mysql
Next, you’ll need to run a simple security script which enables you to:
- set a password for root accounts
Remove the following:
- root accounts that are accessible from outside the local host
- anonymous-user accounts
- the test database, which by default can be accessed by anonymous users
sudo mysql_secure_installation
Afterward, you’ll be asked to set up your root password. For this tutorial, we’re going to select Y first and then choose 0 – to enter our own password without validations.
Since we’ll be accessing MySQL as a root user, we’ll need to set the root password from
auth_socket
to
mysql_native_password
sudo mysql -u root -p <br>
Next, type in the below statement to verify that the root has an auth socket password set in.
SELECT user,authentication_string,plugin,host FROM mysql.user;
Third, type in the below line and replace the ‘password’ field with your preferred password.
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';<br>
Flush the changes so that MySQL saves them.
FLUSH PRIVILEGES;
If you check the root password now using the below command, you should see that the plugin has now changed from auth_socket to mysql_native_password.
SELECT user,authentication_string,plugin,host FROM mysql.user;
Type in `exit` to exit the MySQL environment.
Install PHP Server
Step 5: Install PHP
This step is going to install PHP as our backend language, allowing us to serve our data via REST API. The backend language helps us connect our frontend with our database to display dynamic data. Execute the command below and it shall install all the necessary components.
sudo apt install php libapache2-mod-php php-mysql<br>
Enter ‘Y’ wherever it asks for permission to install the packages.
Verify if PHP has been installed on the server by running in the following command.
php -v
This will return the version of PHP on the server which verifies our installation process.
Step 6: Installing phpmyadmin
This is an add-on step. Since many of us prefer using an interface to interact with the database, this step is crucial.
Using phpMyAdmin makes it easier for you to quickly manage your database with a user-friendly graphical interface.
sudo apt install phpmyadmin php-mbstring php-gettext
Press “Y” and “Enter” whenever the terminal asks you for your permission.
Next, you’ll see a pop up that has ‘apache2’ selected.
Please note that you’ll have to hit SPACE, TAB and then ENTER to ensure that Apache2 is selected and all the files are installed correctly.
Now, type your phpmyadmin password. Our phpMyAdmin software should now be installed! Next up, the only task you need to do in order to access your database is to include an extension and restart the apache2 server.
To enable the extension, type in the line below and press ENTER.
sudo phpenmod mbstring<br>
Next, to restart the apache2 server:
sudo service apache2 restart
You’ll be able to access phpmyadmin terminal with the following URL: http://SERVER_IP/phpmyadmin
Set Up the Database
After you login to your phpmyadmin terminal using your username and password, this is what you’ll see. On the left-hand side is the list of databases available.
Step 7: Let’s create a demo database by clicking on ‘New’
We’ll name our database ‘demo’.
When you click on ‘Create’, you’ll see a demo database is created on your left-hand side.
Now it’s time to create a table ‘test_table’ with 1 column.
Next, we’ll add the column details we want to store in our table. So we want to store emails, hence we’ll name our column – ‘email’ with the type being VARCHAR and the max-length would be 32.
Click on ‘Save’ to save the table configuration.
Now in order to dump a sample entry, click on ‘Insert’ on the top menu.
Enter any email you want to store and click on ‘Go’.
Now select ‘Browse’ from the top menu, and it will look something like this.
PS. If you’re seeing red color popups then click on ‘Ignore all’ to dismiss them. These are just warnings that appear due to some phpmyadmin default settings.
Step 8: Serve JSON data
Perfect. Now, our database is set up. We’ve also set up a table and dumped a sample entry inside it.
All we need to do is now serve the entry from the database and display it in JSON format.
To do this go back to your terminal and navigate to your html folder (public_html) where you’ll store all your scripts and html files.
cd /var/www/html
Type in `ls` to view what are the contents in the current directory.
Next, we’ll need to create a PHP file to connect and serve our data from the database.
I’ll be using the NANO editor for this.
sudo nano index.php
This creates an index.php file inside our directory:
Afterward, paste the below code to serve the entry in JSON format.
<?php $servername = "localhost"; $username = "root"; $password = "your_password"; $db_name = "demo"; $conn = new mysqli($servername, $username, $password, $db_name); $sql = "SELECT email FROM test_table"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo json_encode($result->fetch_assoc()); exit; } ?>
To save the file, use the commands below.
CTRL + X Y Enter
Next, type in the URL in the browser to get the JSON data: http://SERVER_IP/index.php
Conclusion
That’s it! Now you’ve learned how to serve data via REST API! With the help of this tutorial you not only learned how to launch a VPS, but also learned how to set up a web server, install PHP, PhpmyAdmin and MySql in it.
After learning this process, you can now set up your own website, communicate with the backend from frontend and vice versa to perform specific tasks. This includes serving the user’s personal details updating the user’s password.
This tutorial helps establish core fundamentals that are needed to set up a fully functional website and serving JSON data was just an example of what you can build. REST API isn’t as intimidating
Use promo code “SKY95JSONPHP” to save 95% off your first month. Offer is valid for new users only.
About the author: Shantanu Johri is a full-stack developer and a passionate blogger. He is also the founder of Crazythemes where he writes about WordPress, HTML and cloud hosting.