How to run PHP from the command line in Linux

- by

php-med-transDid you know that you can run PHP directly from the command line? Here’s how:

Running a command

Let’s run a one-liner and see the output displayed in our console. We’ll use phpinfo() because we know it should generate a lot of text. We need to start our line with php, use the -r switch and specify our command in single quotes:

php -r 'phpinfo();'

That’s it. You should see a familiar long list of set variables and info about your PHP environment. Note that you have to specify the semicolon inside your brackets, just like you would at the end of any PHP command.

You can also run several commands in a row:

php -r 'echo "Hello "; echo "Jay";'

Notice that when we use single quotes to encapsulate the command, we can use double quotes inside it.

Running a script

You can execute an entire php file from the command line too. Unlike other shell commands, when called with the php parameter there’s no need to change the file permissions. The file does not need to end with .php either.

Consider the following simple script – let’s call it “test.php”. Note the use of the opening and closing php tags, just like we’d use them for web output.


We can run this script from our command line like this:

php -f test.php

You can also run the same script “Linux Shell Command Style” without specifying php first. You need to modify your script in two ways for this to work.

First, we need to include the path to PHP at the beginning of the script, like we’d do with Python or BASH scripts. We do this so that our shell knows how to run the script. The UNIX shebang will look familiar:

#!/usr/bin/php

We also need to change the permissions to allow execution, again like we’d do with other scripts.

chmod +x test.php

Now we can run it like this:

./test.php


If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

4 thoughts on “How to run PHP from the command line in Linux”

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.