Execute PHP files locally

Q I'm having trouble with browsing .php files on my Linux (Mandriva 2007 Free) machine. It keeps trying to open them with KWrite instead of just running them. As I'm currently trying to teach myself PHP, when I'm running an HTML file that calls a PHP process I really don't want to look at the code - I want the PHP to just, well, run.

A You don't run PHP files from a file manager. PHP is a server-side scripting language, so you need to load the PHP page from a web server into your browser. Locally, they are just text files, and your file manager will perform whatever action it is configured to do on text files - in your case to load them into KWrite. This means you need to run your own web server, which is nowhere near as scary as it sounds. Fire up the Mandriva Control Center, go into the software installation section, type 'mod_php' into the Search box and select apache-mod_php-5 for installation. This will also install various other packages that you need to serve PHP files.

When the installation is complete, go into the System section of the Control Center and select the System Services item. Ensure that httpd (the Apache process) is set to start on boot and, if it is not running now, start it. Point your browser at http://localhost and you should see the Apache test page, or maybe just an 'It works!' page, confirming that you now have a working web server. Now all you need to do is put your PHP files in the web server's DocumentRoot, the directory where it looks for files to serve. Mandriva defaults to using /var/www/html for this, so save the following as /var/www/html/test.php:


Load http://localhost/test.php into your browser and you should see some information about the server and the system running it. If so, Apache is not only installed, it is set up to serve PHP pages and you can continue learning the language. Good luck! You may run into permissions problems editing files as your normal user for inclusion in the DocumentRoot directory. This can be solved by adding your user to the Apache group and setting the directory to be writable by member of that group, by typing this in a root terminal:

gpasswd -a yourusername apache
chgrp apache /var/www/html
chmod g+w /var/www/html

You will need to log out and back in again for this to take effect.

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar