Remember: PHP is scripting language!

One of the oft-overlooked aspects of PHP is that you can write scripts in PHP to execute from the command line. I fell into the habit of writing data munging scripts in Perl, and web pages using PHP; I realized I was keeping alive two types of code needlessly.

How do you do this on a Linux machine? Let’s say you have a script called make-ducks.php

First, find out where your PHP engine is:

whereis php

You’ll get back an answer that looks something like this:

php: /usr/local/bin/php /usr/local/lib/php /usr/local/lib/php.ini

The /usr/local/bin/php is your PHP engine. Now simply insert the following at the top of a PHP script you want to run from the command line:

#!/usr/local/bin/php -q

Make sure this is the first line in your PHP script. You can then leave everything else in the PHP script as you would have it otherwise. Mark the PHP script as executable:

chmod +x make-ducks.php

Now you can go ahead and run the script like it was a regular Linux command:

./make-ducks.php

The only difference is that output that normally goes to the browser, including error messages, will now be printed in your terminal window.

Neato!

Comments

Ken's picture
As a hack since DOS batch file days thank you opening doors to these new script languages, most of which I can ‘get’ but have no clue where to start with them.
Deane's picture
Something to remember: all PHP code still has to be within PHP delimiters in the script file. If you’re coming from the Windows side, you may not realize this because VBScript files didn’t need ASP delimiters.

Post new comment

You can comment anonymously if you must, but I would prefer it if you used your real name.
The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
Optional. If you enter the address of a website here, your name will be publicly linked to the site.
  • Adds typographic refinements.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.