When you set up a web server, one of the most common issues you may encounter is seeing raw PHP code in your browser rather than the intended output. This typically indicates that your server isn’t properly processing the PHP files. Let’s dive deep into this issue and explore solutions tailored to both Debian and RHEL-based systems.
Why Does This Happen?
This issue primarily arises when:
- The PHP module isn’t installed or correctly configured with Apache.
- The .php file isn’t associated with the PHP module in the Apache configuration.
- There’s a misconfiguration in your .htaccess file.
1. Installing and Configuring PHP
Before troubleshooting, ensure you have PHP and the necessary Apache PHP module installed.
- On Debian-based Systems (e.g., Ubuntu):
sudo apt update
sudo apt install php libapache2-mod-php
- On RHEL-based Systems (e.g., CentOS, Fedora):
sudo yum install php php-common
sudo yum install php-fpm
- Ensure PHP is enabled in Apache: For both systems, ensure the PHP module is enabled:
sudo a2enmod phpX.X
Replace X.X with your PHP version, e.g., 8.2.
2. Check Apache Configuration for PHP Files
The Apache configuration file should tell the server to process .php files with the PHP module.
- On Debian-based Systems: Open the Apache configuration file:
sudo nano /etc/apache2/apache2.conf
Ensure you have:
<FilesMatch ".+\.php$"> SetHandler application/x-httpd-php </FilesMatch>
- On RHEL-based Systems: Open the Apache configuration file:
sudo nano /etc/httpd/conf/httpd.conf
Ensure you have:
<FilesMatch ".+\.php$"> SetHandler application/x-httpd-php </FilesMatch>
3. Verify .htaccess File
If you’re using an `.htaccess` file to customize the directory configurations, ensure there are no directives preventing the correct execution of PHP files.
Check for lines like `php_value` or `php_flag` and ensure they’re correctly configured or temporarily comment them out for testing.
4. Restart Apache
After making changes, always restart the Apache server.
- On Debian-based Systems:
sudo systemctl restart apache2
- On RHEL-based Systems:
sudo systemctl restart httpd
5. Double Check File Extensions
A minor point, but ensure your PHP files have the correct .php extension. Apache will only process files as PHP if they have the correct file extension.
6. Check for Errors
Inspect the Apache error logs for potential clues:
- On Debian-based Systems:
sudo tail /var/log/apache2/error.log
- On RHEL-based Systems:
sudo tail /var/log/httpd/error_log
Conclusion
Seeing raw PHP code instead of the expected web page can be frustrating, but with methodical troubleshooting, the issue can be quickly resolved. By ensuring PHP is properly installed, checking Apache’s configuration, and inspecting the .htaccess file, you can ensure your server processes PHP files correctly.