How to pass GET variables to php file with Shell? [duplicate] - php

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.

Related

How to pass and read parameters while php.exe compile process on Windows (cmd)

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

Define variable in command line

OK, the question is simple though I can't find a real working solution.
I want to be able to define something while invoking a specific script.
I have tried it like php -d DEBUG_ON myscript.php but it's not working (when testing if (defined("DEBUG_ON")) { } inside the script, it returns false)
Also tried something along the lines of php -r ('define("DEBUG_ON",1);') myscript.php; which doesn't work either.
So, any ideas? (Or any suggestions on how I could achieve the very same effect?)
Use $argv to pass arguments from command line. Then define them accordingly in the beginning of the script.
if(php_sapi_name() === 'cli') {
define('DEBUG_ON', $argv[1]);
}
If you put this code in the beginning of your script, it should then define DEBUG_ON to whatever you pass as argument from commandline: php myscript.php arg1
You can also define($argv[1], $argv[2]); and then use php myscript.php DEBUG_ON 1 to define DEBUG_ON as 1.

calling exec on a php file and passing parameters?

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.

Calling PHP function with arguments remotely

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&params[]=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.

php $GLOBALS variables

I'm writing a bit of the code and I have parent php script that does include() and includes second script, here is snippet from my second code:
echo ($GLOBALS['key($_REQUEST)']);
I'm trying to grab a key($_REQUEST) from the parent and use it in child, but that doesn't work..
this is when I run script using command line:
mbp:digaweb alexus$ php findItemsByKeywords.php test
PHP Notice: Undefined index: key($_REQUEST) in /Users/alexus/workspace/digaweb/findItemsByKeywords.php on line 3
PHP Stack trace:
PHP 1. {main}() /Users/alexus/workspace/digaweb/findItemsByKeywords.php:0
mbp:digaweb alexus$
i heard that globals isn't recommended way also, but i don't know maybe it's ok...
$_REQUEST is a superglobal and will be directly available inside of any function or script, so you don't need to worry about passing it to the child script. However, PHP won't populate $_REQUEST when used from the command line, unless you're using a configuration option I'm unfamiliar with. You'll need to use the $_SERVER['argv'] array.
Globals are indeed not recommended. You'll have an easier time long-term if you go with what outis suggested. Here's an example:
script1.php:
<?php
$file = $_SERVER['argv'][1]; // 0 is the script's name
require_once ('script2.php');
$result = doSomething ($file);
echo $result;
?>
script2.php:
<?php
function doSomething ($inputfile)
{
$buf = file_get_contents($inputfile);
$buf = strtolower($buf); // counts as something!
return $buf;
}
?>
This example doesn't make use of the key($_REQUEST), but I'm not sure what the purpose of that is so I just went with $_SERVER['argv'].
Based on your comment to my other answer, I think I understand what you're trying to do. You're just trying to pass a variable from one script into another script that's included.
As long as you define a variable before you include the script, it can be used in the included script. For instance:
// script1.php
$foo = 'bar';
include_once('script2.php');
// script2.php
echo $foo; // prints "bar"
echo $_GLOBALS[key($_REQUEST)];
You just need to remove the single quotation marks. It was looking for the literal 'key($_REQUEST)' key, which obviously doesn't exist.
It all depends on what you are trying to do though... what are you trying to do?

Categories