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.
I working in Rails and I need to call to an PHP-script.
I can connect to the script like this:
system('php public/myscript.php')
But I need to send some parameters with it.
How do I do that?
Thanks
You can provide command-line arguments to your PHP script:
system('php public/myscript.php arg1 arg2')
They will be available from your PHP code like this:
echo $argv[0]; // public/myscript.php
echo $argv[1]; // arg1
echo $argv[2]; // arg2
You can just specify the parameters on the command line, such as system('php -f public/myscript.php argument1 argument2 [...]') and they will be available in the $argv[] array, starting from $argv[1]. See the doc page here for more info.
Yes its right way to use system('php public/myscript.php arg1 arg2') as SirDarius answered .
but system command will return the true or false in that case.
system() will return TrueClass or FalseClass and display output, try it on console .
I suggest , You can use the open method on any URL to call it, so you can call your PHP script using that:
require 'open-uri'
open('YOUR PHP SCRIPT PATH WITH PARAMETER') do |response|
content = response.read
end
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.
Say we usually it access via
http://localhost/index.php?a=1&b=2&c=3
How do we execute the same on a Linux command prompt?
php -e index.php
But what about passing the $_GET variables? Maybe something like php -e index.php --a 1 --b 2 --c 3? I doubt that'll work.
From this answer on Server Fault:
Use the php-cgi binary instead of just php, and pass the arguments on the command line, like this:
php-cgi -f index.php left=1058 right=1067 class=A language=English
Which puts this in $_GET:
Array
(
[left] => 1058
[right] => 1067
[class] => A
[language] => English
)
You can also set environment variables that would be set by the web server, like this:
REQUEST_URI='/index.php' SCRIPT_NAME='/index.php' php-cgi -f index.php left=1058 right=1067 class=A language=English
Typically, for passing arguments to a command line script, you will use either the argv global variable or getopt:
// Bash command:
// php -e myscript.php hello
echo $argv[1]; // Prints "hello"
// Bash command:
// php -e myscript.php -f=world
$opts = getopt('f:');
echo $opts['f']; // Prints "world"
$_GET refers to the HTTP GET method parameters, which are unavailable on the command line, since they require a web server to populate.
If you really want to populate $_GET anyway, you can do this:
// Bash command:
// export QUERY_STRING="var=value&arg=value" ; php -e myscript.php
parse_str($_SERVER['QUERY_STRING'], $_GET);
print_r($_GET);
/* Outputs:
Array(
[var] => value
[arg] => value
)
*/
You can also execute a given script, populate $_GET from the command line, without having to modify said script:
export QUERY_STRING="var=value&arg=value" ; \
php -e -r 'parse_str($_SERVER["QUERY_STRING"], $_GET); include "index.php";'
Note that you can do the same with $_POST and $_COOKIE as well.
Sometimes you don't have the option of editing the PHP file to set $_GET to the parameters passed in, and sometimes you can't or don't want to install php-cgi.
I found this to be the best solution for that case:
php -r '$_GET["key"]="value"; require_once("script.php");'
This avoids altering your PHP file and lets you use the plain php command. If you have php-cgi installed, by all means use that, but this is the next best thing. I thought this options was worthy of mention.
The -r means run the PHP code in the string following. You set the $_GET value manually there, and then reference the file you want to run.
It's worth noting you should run this in the right folder, often, but not always, the folder the PHP file is in. 'Requires' statements will use the location of your command to resolve relative URLs, not the location of the file.
I don't have a php-cgi binary on Ubuntu, so I did this:
% alias php-cgi="php -r '"'parse_str(implode("&", array_slice($argv, 2)), $_GET); include($argv[1]);'"' --"
% php-cgi test1.php foo=123
<html>
You set foo to 123.
</html>
%cat test1.php
<html>You set foo to <?php print $_GET['foo']?>.</html>
Use:
php file_name.php var1 var2 varN
Then set your $_GET variables on your first line in PHP, although this is not the desired way of setting a $_GET variable and you may experience problems depending on what you do later with that variable.
if (isset($argv[1])) {
$_GET['variable_name'] = $argv[1];
}
The variables you launch the script with will be accessible from the $argv array in your PHP application. The first entry will the name of the script they came from, so you may want to do an array_shift($argv) to drop that first entry if you want to process a bunch of variables. Or just load into a local variable.
Try using WGET:
WGET 'http://localhost/index.php?a=1&b=2&c=3'
Option 1: php-cgi
Use 'php-cgi' in place of 'php' to run your script. This is the simplest way as you won't need to specially modify your PHP code to work with it:
php-cgi -f /my/script/file.php a=1 b=2 c=3
Option 2: If you have a web server
If the PHP file is on a web server you can use 'wget' on the command line:
wget 'http://localhost/my/script/file.php?a=1&b=2&c=3'
Or:
wget -q -O - "http://localhost/my/script/file.php?a=1&b=2&c=3"
Accessing the variables in PHP
In both option 1 & 2, you access these parameters like this:
$a = $_GET["a"];
$b = $_GET["b"];
$c = $_GET["c"];
If you have the possibility to edit the PHP script, you can artificially populate the $_GET array using the following code at the beginning of the script and then call the script with the syntax: php -f script.php name1=value1 name2=value2
// When invoking the script via CLI like
// "php -f script.php name1=value1 name2=value2",
// this code will populate $_GET variables called
// "name1" and "name2", so a script designed to
// be called by a web server will work even
// when called by CLI
if (php_sapi_name() == "cli") {
for ($c = 1; $c < $argc; $c++) {
$param = explode("=", $argv[$c], 2);
$_GET[$param[0]] = $param[1]; // $_GET['name1'] = 'value1'
}
}
If you need to pass $_GET, $_REQUEST, $_POST, or anything else you can also use PHP interactive mode:
php -a
Then type:
<?php
$_GET['a'] = 1;
$_POST['b'] = 2;
include("/somefolder/some_file_path.php");
This will manually set any variables you want and then run your PHP file with those variables set.
At the command line, paste the following:
export QUERY_STRING="param1=abc¶m2=xyz" ;
POST_STRING="name=John&lastname=Doe" ; php -e -r
'parse_str($_SERVER["QUERY_STRING"], $_GET); parse_str($_SERVER["POST_STRING"],
$_POST); include "index.php";'
I just pass them like this:
php5 script.php param1=blabla param2=yadayada
It works just fine. The $_GET array is:
array(3) {
["script_php"]=>
string(0) ""
["param1"]=>
string(6) "blabla"
["param2"]=>
string(8) "yadayada"
}
Use:
php -r 'parse_str($argv[2],$_GET);include $argv[1];' index.php 'a=1&b=2'
You could make the first part as an alias:
alias php-get='php -r '\''parse_str($argv[2],$_GET);include $argv[1];'\'
Then simply use:
php-get some_script.php 'a=1&b=2&c=3'
Or just (if you have Lynx):
lynx 'http://localhost/index.php?a=1&b=2&c=3'
Hi there are multiple specific examples but I just wanted to have a working generic calling PHP into background example from shell_exec.
So my php function runs a large processing job.
On the top of the script (process.php) I put?
!#usr/bin/php
i think - any way to get that specific path, maybe 'which php'?
then the actual command is
shell_exec(sprintf('php process.php %s %s > /dev/null 2>/dev/null &','data1','data2'));
and access the data from process.php with argsv[1] and argsv[2]
?
thanks
You can definitely access the arguments from process.php the way you described, but why would you want to kick off process.php like that?
If you're already in a php shell script, why not just include the process.php file?
You need to run curl multi exec on your php script with a parameter and receive an answer after run, like: http://localhost/phpjob.php?par1=asdasd&par2=1212....