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
As a hack since DOS batch
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.
Something to remember: all
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.
Add new comment