Thursday, March 22, 2007

PHP on the command line

If you want to run .php files from the command line,
eg. for file manipulation with no browser output or whatever, check out

To elaborate, I used to use freebasic or qbasic for programming little scripts that convert between one type of ascii data file and another. I used to read in a .CSV file into freebasic and check each line for commas and seperate the text - it was painful. Since I've learned a bit about PHP I can now use the Explode and implode commands in PHP - Explode will take apart a line of text that's seperated by commas, tabs, newlines, whatever you specify, and it will create an array for you with all the data. It makes the type of programming I did a million times simpler. For this reason I wanted to get PHP working on the command line. Now I can read in csv files and stick them on a MySQL database with ease.... ah how I love programming. I can also use the windows command-line "at" command to schedule the run of PHP. Of course this is all slightly different on a Linux box with "cron" being used instead of "at" etc. and the PHP command line parameters might be different. but you get the idea.

Oh yeah "implode" does the exact opposite of "explode".

Something to watch out for:
Check your PHP.ini - the line that says "extension_dir ="
For example, on my system I use uniform server, which I'll explain in another post.
I keep my uniform server on d:\uniserver so the line line in my php.ini said:


This meant that the extensions couldn't load from my current path where I was keeping my PHP files

How I got it to work was as follows (this will be different for you depending on where your copy of PHP is stored):
  1. I made a copy of my php.ini into my D:\ (anywhere will do)
  2. I changed the line to say extension_dir = "d:/uniserver/diskw/usr/local/PHP/extensions"
  3. Then if I'm in a directory and I have a PHP file called 1.php I could run PHP like so:
d:\uniserver\diskw\usr\local\php\php.exe -c d:\php.ini 1.php

It would echo out any echo stuff from within the PHP to the console, and will run any MySQL queries or whatever. It's nice. If you have any trouble with it, you can email me on

No comments: