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:
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:
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:
The only difference is that output that normally goes to the browser, including error messages, will now be printed in your terminal window.