calling exec on a php file and passing parameters?

this adapted script shows 2 ways of passing parameters to a php script from a php exec command: CALLING SCRIPT

<?php 
$fileName = '/var/www/ztest/helloworld.php 12';
$options = 'target=13';
exec ("/usr/bin/php -f {$fileName} {$options} > /var/www/ztest/log01.txt 2>&1 &");

echo "ended the calling script"; 
?>

CALLED SCRIPT

<?php
echo "argv params: ";
print_r($argv); 
if ($argv[1]) {echo "got the size right, wilbur!  argv element 1: ".$argv[1];}
?> 

dont forget to verify execution permissions and to create a log01.txt file with write permissions (your apache user will usually be www-data).

RESULT

argv params: Array

(

[0] => /var/www/ztest/helloworld.php

[1] => 12

[2] => target=13

)

got the size right, wilburargv element 1: 12

choose whatever solution you prefer for passing your parameters, all you need to do is access the argv array and retrieve them in the order that they are passed (file name is the 0 element).

tks @hakre


If you want to pass a GET parameter to it, then it's mandatory to provide a php-cgi binary for invocation:

exec("QUERY_STRING=id=123 php-cgi /var/www/emailer.php");

But this might require more fake CGI environment variables. Hencewhy it is often advisable to rewrite the called script and let it take normal commandline arguments and read them via $_SERVER["argv"].

(You could likewise just fake the php-cgi behaviour with a normal php interpreter and above example by adding parse_str($_SERVER["QUERY_STRING"], $_GET); on top of your script.)


Your call is failing because you're using a web-style syntax (?parameter=value) with a command-line invokation. I understand what you're thinking, but it simply doesn't work.

You'll want to use $argv instead. See the PHP manual.

To see this in action, write this one-liner to a file:

<?php print_r($argv); ?>

Then invoke it from the command-line with arguments:

php -f /path/to/the/file.php firstparam secondparam

You'll see that $argv contains the name of the script itself as element zero, followed by whatever other parameters you passed in.


try echo exec("php /var/www/unity/src/emailer.php 123"); in your script then read in the commandline parameters.