Remember: PHP is scripting language!

Peter Rukavina

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

Submitted by Ken on

Permalink

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.

Submitted by Deane on

Permalink

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

Plain text

  • Allowed HTML tags: <b> <i> <em> <strong> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

About This Blog

Photo of Peter RukavinaI am . I am a writer, letterpress printer, and a curious person.

To learn more about me, read my /nowlook at my bio, listen to audio I’ve posted, read presentations and speeches I’ve written, or get in touch (peter@rukavina.net is the quickest way). 

You can subscribe to an RSS feed of posts, an RSS feed of comments, or a podcast RSS feed that just contains audio posts. You can also receive a daily digests of posts by email.

Search