How to run a PHP script from a Unix command line

PHP FAQ: How can I run a PHP script from the Linux/Unix command line?

Solution: To run a PHP script from a Unix command line you can use this syntax:

php -f myscript.php

That assumes that the file myscript.php is a legal PHP script.


For instance, while I was just trying to figure out a PHP date/format problem I used that command on a script named datetest.php that has this content:

$d = date("Y-m-d H:i:s");
echo "$d\n";

Here’s what that PHP command and its output looks like when I run it from my Unix command line:

$ php -f datetest.php
2019-10-02 18:48:12

Run PHP at the Linux/Unix command line

Note that for little tests like this you can also execute PHP code right at the Unix command line using php -r:

$ php -r '$d = date("Y-m-d H:i:s"); echo "$d\n"; '
2019-10-02 18:52:35

One key I found with this approach is to use single-quotes to enclose your PHP code. If you use double-quotes the Unix shell will attempt to interpret whatever is inside your string.