Saturday, February 7, 2009

Accessing command line from PHP code

It is sometimes necessary (or easier) to execute command line commands from within PHP code, in this post I will show an example of such usage. If you only need an ├╝ber-basic example, here it is:


$thisf = $_SERVER['SCRIPT_NAME'];
$thisf newname.php`;


This little piece of code will copy the running script to newfile.php. If you're not satisfied yet, keep reading.

The scenario: You have a folder with lots of .zips, and you want to unzip each one in to a relevant folder according to it's name's first letter. For example if the .zip's name is we'll unzip it to dir s, if it's name is we'll unzip it to dir a. To keep the code short we assume that all needed directories already exist and that there are only .zips in the src dir.

Before we dive in to PHP lets go over the Linux command line unzip. To unzip residing in dir src to dir trg you use the following command:

$ unzip -d trg src/

Finally, ladies and gentlemen, the code:
//directory where the zips reside
$srcdir = "/home/user/zips/";

//the output master directory inside we have all the letters
$trgdir = "/home/user/out/";

$dirh = opendir($srcdir); //the dir handler of the zips

while(($zip = readdir($dirh)) !== FALSE) { //reading next file in dir
if($zip == "." || $zip == "..") continue; //checking that those are actual files

$firstL = $zip[0]; //getting the first letter of the file
`unzip -d $trgdir$firstL $srcdir$zip`; //running the CLI command

Comments and questions are very welcome!

No comments:

Post a Comment