How to run PHP from the command line in Linux

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:

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:

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:

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:

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

Now we can run it like this:

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

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

Leave a Reply to Cyd Cancel reply