Linux – PHP works on command line but not in browser

apache-http-servercommand linelinuxPHPraspbian

When I run a basic 'hello world' php script from the command line, running the command php test.php, it returns a valid html page. However, when I try to access it by a browser, I get the text of the php script returned, rather than valid html.

The php script "test.php" is as follows:

<html>
<head>
  <title>PHP Test</title>
</head>
<body>
  <?php

     echo '<p>Hello World</p>';

   ?>
</body>
</html>

I am running Apache on Raspbian.

Best Answer

PHP may run in different modes of operation.

It can be console interpreter when you run it from command prompt, or it can run as CGI, also can run as a service - php-fpm, it can run as apache's module or it can be a web server itself.

The simplest way to run your php scripts in browser it use its embedded web server.
Just run php -S ip.ip.ip.ip:port -t /path/to/directory/where/php/files/lives substitute ip.ip.ip.ip with IP address assigned to Raspberry Pi (get it from ifconfig) and substitute port with port you want embedded server will listen for connection (let it be 8000). If you point your browser to http://ip.ip.ip.ip:port/your-script.php you will get what you want without need to run apache at all.

If you still want to run php via apache, you need to figure out how did you install it.

Steps to check if php should run as apache module:
Run apache2ctl -M and look if php module loaded. If it isn't there then you need to enable it sudo a2enmod phpX (where X is php version) and reload apache with command:
sudo service apache2 reload.

Steps to check if php should run as php-fpm service:
If you install php as php-fpm service then you need to check if it is running :
ps aux | grep 'php-fpm'
If it running then you need configure your apache instance to work as proxy. Use official apache documentation to set it up. It is more complicated setup to compare with a case when php runs as apache module but it has many advantages that usually need in production environment.

Steps to check if php should run as php-cgi (in this mode php called by apache every time when someone request php file ):
Check apache's config file(s) for the presence following settings:

ScriptAlias /local-bin /usr/bin
AddHandler application/x-httpd-php5 php
Action application/x-httpd-php5 /local-bin/php-cgi