27 Jul
PHP Code in The Background Part 2
The blog entry How To Run PHP Code In The Background discussed how to run a php file through the command line using php's exec() command. Recently, I needed to pass a querystring to the php file, but this is not possible through the command line. If you try to pass a querystring, the exec() command will fail.
Fortunately, after some googling, I came across a forum post that mentioned how the global array $_SERVER["argv"] can be used to get arguments being passed through php. I then followed the link on that page to Chapter 43. Using PHP from the command line on the php.net website. Under the user contributed notes, I found a nice little function for getting the arguments and placing them into an array, similar to $_GET, $_POST, and $_REQUEST.
Let's take the example from the original How To Run PHP Code In The Background blog entry.
resize_exec.php
Now, let's take a look at the code for image_resize.php
image_resize.php
Fortunately, after some googling, I came across a forum post that mentioned how the global array $_SERVER["argv"] can be used to get arguments being passed through php. I then followed the link on that page to Chapter 43. Using PHP from the command line on the php.net website. Under the user contributed notes, I found a nice little function for getting the arguments and placing them into an array, similar to $_GET, $_POST, and $_REQUEST.
Let's take the example from the original How To Run PHP Code In The Background blog entry.
resize_exec.php
<%
$command = "/usr/bin/php4 -f /var/www/myweb/image_resize.php";
exec( "$command > /dev/null &", $arrOutput );
%>Now, let's say I want to allow the user to enter a directory and image width when executing the command. Here's the updated code.<%
$command = "/usr/bin/php4 /var/www/myweb/image_resize.php --dir=/var/www/myeb/images --width=250";
exec( "$command > /dev/null &", $arrOutput );
%>Notice that the -f option has been removed, since it appears that that option removes the first argument after the file name. Use the double dash to identify an argument with a key/value pair.Now, let's take a look at the code for image_resize.php
image_resize.php
<%
$_ARG = arguments($_SERVER['argv']);
$dir = $_ARG["dir"];
$width = $_ARG["width"];
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
$_ARG[$reg[1]] = $reg[2];
} elseif(ereg('-([a-zA-Z0-9])',$arg,$reg)) {
$_ARG[$reg[1]] = 'true';
}
}
return $_ARG;
}
print "dir = $dir<br />";
print "width = $width<br />";
%>image_resize.php outputNow you can setup any php script file to accept arguments through a command line.dir =/var/www/myeb/images
width = 250
From the Workbench, PHP
by Ken Foubert | 7/27/2007 2:56pm
by Ken Foubert | 7/27/2007 2:56pm
No comments found.