PHP Not Running from Command Line on macOS – How to Fix

macososx-serverPHP

When trying to run a PHP script from inside Terminal, the script is just echoed to stdout. This happens if the script is executed directly (first line #!/usr/bin/php) called as an argument (/usr/bin/php ./test.php), or if the php command(s) is input interactively.

What could be the problem?

Computer is El Capitan Server, 10.11.6; and, no extra MAMP/Apache/PHP has been installed. On a non-server El Capitan machine, things work as expected; so, I'm stumped…

Adding output of ls command:

sh-3.2# ls -lFa /usr/bin/php
-rwxr-xr-x  1 root  wheel  10577264 Jul  9 11:51 /usr/bin/php*
sh-3.2# 

Adding more output:

sh-3.2# ls -lFa /var/root/test.php
-rwxr-xr-x  1 root  wheel  17 Nov 21 16:48 /var/root/test.php*
sh-3.2# cat /var/root/test.php
<?
phpinfo();
?>
sh-3.2# /usr/bin/php /var/root/test.php
<?
phpinfo();
?>
sh-3.2# od -c /var/root/test.php
0000000    <   ?  \n   p   h   p   i   n   f   o   (   )   ;  \n   ?   >
0000020   \n                                                            
0000021
sh-3.2# od -x /var/root/test.php
0000000      3f3c    700a    7068    6e69    6f66    2928    0a3b    3e3f
0000020      000a                                                        
0000021
sh-3.2# 

Best Answer

Use the long tag like

<?php
phpinfo();

in test.php instead of your somehow malformed test.php and it should work.