I have a scenario where in our php file accepts parameters from the command line.
For example we say,
php test.php 'hello'
Now the above runs on command prompt. Suppose now we want to invoke this from client end however ofcourse i do not want the System system call as that would be a bad design, i just want to directly call the function which accepts parameters from the client end and ofcourse client can be anything maybe .Net or PHP so how can I caccomplish that?
Thanks!
Put your script on a web server and accept the argument via HTTP GET or POST.
It would look something like http://hostname/test.php?argument=hello. Then, in your test.phpscript, pass the $_GET['argument'] to your function:
myfunction($_GET['argument']);
Don't forget to sanitize the input!
you may use a function that will manage command line argiments:
$param_1 = isset($argv[1]) ? $argv[1] : null;
if ($param_1 == 'function1')
function1()
elseif...
and so on.
You can make a wrapper script that puts GET parameters from your client into the command line argument array.
Let's say your client makes a request like:
hostname/testWrapper.php?params[]=hello¶ms[]=goodbye
Your wrapper script testWrapper.php could then look like
<?php
$params = $_GET['params'];
foreach ($params as $i => $param)
$_SERVER['argv'][$i + 1] = $param;
$_SERVER['argc'] = count($_GET['params'] + 1);
include ('test.php');
?>
This assumes that your test.php uses $_SERVER['argv/argc']to read command line arguments. It may use $argv and $argc instead (if 'register_argc_argv' is enabled in your php.ini), in which case you just use those in your wrapper script instead of $_SERVER[...].
Notice that we have to insert the parameters with an offset of 1 (i.e. $params[0] becomes $_SERVER['argv'][1]. This is because when the script is called from the command line, the first parameter $_SERVER['argv'][0] is the script name.
Lastly, unless you are absolutely sure that your test.php sanitizes the parameters, you have to do it in the wrapper script.
Related
I have a PHP that receives a parameter (for example 4000) it uses to query a DB with. After executing whatever it needs to do, I want the PHP to call itself so it can do the exact same thing but this time with the new value (for example 8000). Ofocurse I need the first instance to stop/exit/halt.
How can I do this? Include is irrelevant and exec is good for other types of execution (unless I'm wrong here)
Thanks
If you are not required to output anything from the script, you could do the following:
Perform the task while not running into script timeout
Set a location header to the script itself with modified parameters
exit
If you want the script to produce output, you can use the Javascript function location.href instead of the location header. For this, output something like the following snippet at the end of your script:
// php functionality above
?>
<script language="JavaScript">
location.href = "<?php echo $_SERVER['SCRIPT_NAME']; ?>?param=<php echo $param_value; ?>";
</script>
Modify this to fulfill your needs. The header is more suitable for non-interactive setups like the links2 browser, whereas the JavaScript you would use if you want to see whats going on.
You could use recursive functions, which simply means calling the same function from that function. Simple example based on the numbers you gave:
<?php
function do_something( $arg )
{
// Just do something (example)
echo $arg . "\n";
$arg = $arg + 4000;
// Stop doing it when the argument is above 8000
if( $arg > 8000 )
{
return;
}
// Do it again
do_something( $arg );
}
do_something( 4000 );
You can make the script call itself by using the header() method.
Let's say you want to retrieve a batch of 24 rows at every run of a script named whatever.php.
You tell whatever.php to look out for a $_GET parameter. If there is none, you tell it to start from zero when querying the database ("...LIMIT 24"). After you've done what you needed to use header() method in order to call whatever.php again:
header('Location:whatever.php?offset=25');
Now the whatever.php, when called, will know that it must impose an offset to the sql LIMIT ("...LIMIT 25, 24"). After the script done it's job again, you call it again with the header() method:
header('Location:whatever.php?offset=50');
Hope this helps you...
When I use web browser I pass parameters by this way:
http://localhost/script.php?nr=444524
and get it this way:
$var = $_GET('nr');
print_r($var);
but how to achieve the same result (pass and get parameters) when I compile same script with cmd on windows?
c:\php.exe script.php ?nr=444524
this way doesn't work
It doesn't work that way. $_GET is a variable created to feed in data from an HTTP request.
On the command line you enter arguments as:
php script.php 444524
From here you can ready the arguments as print_r($argv);.
All the words you put into the command line, starting with the script name can be found in the global variable $argv. Launch your script with various parameters and check the output of print_r($argv); to see what you get.
Check the documentation here
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP passing $_GET in linux command prompt
i want execute php file with Shell script but i dont know how i can pass GET variables.
This script "php script.php?var=data" don't work because Shell can't find the file "script.php?var=data".
So ,do you know how i can pass my variables ? If it's really impossible to use GET variable, can i pass variables by an other way and use it in my php script ?
If you're executing your script via the command-line (such as php your_script.php), you will not be able to use the $_GET parameters, as you're experiencing.
However, you can make use of PHP's CLI which graciously gives you the $argv array.
To use it, you will call your script like this:
php your_script.php variable1 "variable #2"
Inside your script, you can access the variables with:
<?php
$variable1 = $argv[1];
$variable2 = $argv[2];
?>
My idea would be to write some kind of wrapper script to feed to /usr/bin/php and give that a string of arguments to grab the data from. Make no mistake, it is a hack and probably not a good one at that, but it should get the job done.
<?php
/** Wrapper.php
**
** Description: Adds the $_GET hash to a shell-ran PHP script
**
** Usage: $ php Wrapper.php <yourscript.php> arg1=val1 arg2=val2 ...
**/
//Grab the filenames from the argument list
$scriptWrapperFilename = array_shift($argv); // argv[0]
$scriptToRunFilename = array_shift($argv); // argv[1]
// Set some restrictions
if (php_sapi_name() !== "cli")
die(" * This should only be ran from the shell prompt!\n");
// define the $_GET hash in global scope
$_GET;
// walk the rest and pack the $_GET hash
foreach ($argv as $arg) {
// drop the argument if it's not a key/val pair
if(strpos($arg, "=") === false)
continue;
list($key, $value) = split("=", $arg);
// pack the $_GET variable
$_GET[$key] = $arg;
}
// get and require the PHP file we're trying to run
if (is_file($scriptToRunFilename))
require_once $scriptToRunFilename;
else
die(" * Could not open `$scriptToRunFilename' for inclusion.\n");
?>
PHP CLI takes variables within a command structure like:
php woop.php --path=/home/meow/cat.avi
You can then use something like http://php.net/manual/en/function.getopt.php to get that option like so in your PHP script:
getopt('path')
Or you can get them directly form argv.
As an alternative as #GBD says you can use a bash script to wget a page of your site as well.
I am creating PHP script which is taking arguments from command line right now but after sometime it may change to simply including my PHP script.
How can I prepare my script for both scenarios?
Can I create such PHP script so that it can take argument from command line and from other script which is simply including my script?
let's say script A is the first script that can be called from the commnad line and included in another script and script B is the one that includes it.
if you include script A in B you'll have access to any variable in script B. so why don't you add a check in script A to see if a param has been passed from the command line, if no params have been passed from the command line use whatever variables you created in script B
If I understand well, you'll be forced to use a parameter to tell if your script is using the commandline parameter, or if he will call your other script.
In your script, you can do something like :
if (!strcmp($argv[1], "-s"))
shell_exec('php YourOtherScript.php [put_args_here]');
else
your_current_script($argv);
Then, if you want to execute your other script, you'll make a command like :
php MyScript.php -s [args]
Otherwise, simply put the standard arguments :
php MyScript.php [args]
could be as simple as:
if(isset($argv[1])){
//commadn line arguments
$foo=$argv[1]
}else{
//not
$foo=$foo
}
I am wanting to call a php file using exec.
When I call it I want to be able to pass a variable through (an id).
I can call echo exec("php /var/www/unity/src/emailer.php"); fine, but the moment I add anything like echo exec("php /var/www/unity/src/emailer.php?id=123"); the exec call fails.
How can I do this?
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.
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.)
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
I know this is an old thread but it helped me solve a problem so I want to offer an expanded solution. I have a php program that is normally called through the web interface and takes a long list of parameters. I wanted to run it in the background with a cron job using shell_exec() and pass a long list of parameters to it. The parameter values change on each run.
Here is my solution: In the calling program I pass a string of parameters that look just like the string a web call would send after the ?. example: sky=blue&roses=red&sun=bright etc. In the called program I check for the existence of $argv[1] and if found I parse the string into the $_GET array. From that point forward the program reads in the parameters just as if they were passed from a web call.
Calling program code:
$pars = escapeshellarg($pars); // must use escapeshellarg()
$output = shell_exec($php_path . ' path/called_program.php ' . $pars); // $pars is the parameter string
Called program code inserted before the $_GET parameters are read:
if(isset($argv[1])){ // if being called from the shell build a $_GET array from the string passed as $argv[1]
$args = explode('&', $argv[1]); // explode the string into an array of Type=Value elements
foreach($args as $arg){
$TV = explode('=', $arg); // now explode each Type and Value into a 2 element array
$_GET[$TV[0]] = $TV[1]; // set the indexes in the $_GET array
}
}
//------------------------
// from this point on the program processes the $_GET array normally just as if it were passed from a web call.
Works great and requires minimal changes to the called program. Hope someone finds it of value.