Introduction
Setting up PHP on an Ubuntu server is a crucial step for developers aiming to create dynamic websites or work with PHP-based applications. This tutorial will guide you through the process of installing PHP, configuring your environment, and testing your setup, giving you a robust foundation for your PHP projects.
Installing PHP
To begin, open your terminal, and execute the following command to update your package list:
sudo apt update
With your packages up to date, you can install PHP by typing:
sudo apt install php
Once the installation is complete, you can verify the PHP version using:
php -v
Server Setup
Running PHP requires a web server. Apache2 is widely-used and can be installed with:
sudo apt install apache2
After the installation, start the Apache2 service:
sudo systemctl start apache2
Enable the service to start on boot:
sudo systemctl enable apache2
PHP Configuration
Edit the PHP configuration file, php.ini
, by finding it with:
sudo updatedb
sudo locate php.ini
Open the file with a text editor and make your required changes. For instance, to increase the maximum upload size:
upload_max_filesize = 10M
post_max_size = 10M
Testing PHP
Create a test PHP file info.php
in the web server’s root directory:
sudo echo '
' > /var/www/html/info.php
Now navigate to http://your-server-ip/info.php
. You should see the PHP information page.
Database Management
Most PHP applications require a database. Install MySQL with:
sudo apt install mysql-server
sudo mysql_secure_installation
Connect to the MySQL console using:
sudo mysql -u root -p
Advanced: PHP-FPM and Nginx
For better performance, consider using PHP-FPM with Nginx. Install Nginx and PHP-FPM:
sudo apt install nginx php-fpm
Edit the Nginx configuration to use PHP-FPM by adding the following to your server block:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
Restart Nginx:
sudo systemctl restart nginx
Conclusion
Setting up PHP on Ubuntu involves a series of steps tailoring your server environment. By following this guide, you now have PHP installed and configured for web development, ready to build robust PHP-based applications.