[Practice 4] Host a PHP Dynamic Website on Amazon EC2
Co-author: Allie Hsu
In the previous practice we create our database for storing the data we plan to use, now we are going to use PHP to communicate the Frontend with MySQL on AWS EC2.
Follow the steps below:
- Install Apache and PHP on EC2
- Setting up the Apache and PHP
- Connect to RDS Instance by Using PHP
Install Apache and PHP on EC2
If you have already installed PHP, you can update the packages to the latest available version (the green box in the picture above):
sudo yum update -y
Otherwise, install it:
sudo yum install -y httpd24 php70 php70-mysqlnd
After updating or installing, the processing conflict error might be shown. You can delete the original package to solve this problem before the re-installation.
After re-installing, start the Apache server (the orange box in the picture above):
sudo service httpd start
If the server works, you can see the green ‘OK’ on the screen. You can also check the server configuration. The command below is to turn on a service for the default run levels (2,3,4,5):
sudo chkconfig httpd on
Also, you can view a full list of services:
chkconfig --list
Setting up the Apache and PHP
How to tell Apache which PHP to use? First, we can check your Apache and PHP versions.
httpd -v //apache2.4.39
php -v //php7.0
If PHP does not work, that might be the version problem. Then, you will need to add the command into the file ‘httpd.conf’ by using vim editor:
vim /etc/httpd/conf/httpd.conf
Add the following command into the order as below to execute PHP module in Apache (make sure you load the right version of the module):
LoadModule php5_module modules/libphp7.so
Tips:
In this httpd.conf file, you can also set the first operated file in dir_module, as the screenshot below, now is open index.html.
In addition, you can customize dir_module as DirectoryIndex index.php index.html. That is, this would be the server first finds and executes index.php. If the file index.php is not found, the second order index.html will be executed instead.
Note: The DirectoryIndex command allows you to specify a default page to display when a directory is accessed.
Connect to RDS Instance by Using PHP
In order to get the data from RDS, PHP will do the connecting action with the database information:
DB_SERVER is the RDS endpoint (the red part in the screenshot) and innodb is the name of the initial database (the green part in the screenshot).
When you open the web page, the success message will be displayed on the screen if it connects successfully (the blue part in the screenshot above).
Previous: [Practice 3] Set up Amazon RDS
Next: [Practice 5] Password Protect for the website in EC2 — THE END
Thanks for reading! 😊If you enjoyed it, let's do finger cardio! Try how many times can you hit 👏 in 5 seconds. This will help more people see this story.