Pass a Variable to a PHP Script Running from the Command Line

Pass a variable to a PHP script running from the command line

The ?type=daily argument (ending up in the $_GET array) is only valid for web-accessed pages.

You'll need to call it like php myfile.php daily and retrieve that argument from the $argv array (which would be $argv[1], since $argv[0] would be myfile.php).

If the page is used as a webpage as well, there are two options you could consider. Either accessing it with a shell script and Wget, and call that from cron:

#!/bin/sh
wget http://location.to/myfile.php?type=daily

Or check in the PHP file whether it's called from the command line or not:

if (defined('STDIN')) {
$type = $argv[1];
} else {
$type = $_GET['type'];
}

(Note: You'll probably need/want to check if $argv actually contains enough variables and such)

Run php script from command line with variable

Script:

<?php

// number of arguments passed to the script
var_dump($argc);

// the arguments as an array. first argument is always the script name
var_dump($argv);

Command:

$ php -f test.php foo bar baz
int(4)
array(4) {
[0]=>
string(8) "test.php"
[1]=>
string(3) "foo"
[2]=>
string(3) "bar"
[3]=>
string(3) "baz"
}

Also, take a look at using PHP from the command line.

Run PHP script from CLI and pass parameters

You need to run PHP:

php /my/script.php arg1 arg2

Then in your PHP file:

<?php
// It's 0 based, but arg1 will be at index 1!
var_dump($argv);

PHP, pass parameters from command line to a PHP script

When calling a PHP script from the command line you can use $argc to find out how many parameters are passed and $argv to access them. For example running the following script:

<?php
var_dump($argc); //number of arguments passed
var_dump($argv); //the arguments passed
?>

Like this:-

php script.php arg1 arg2 arg3

Will give the following output

int(4)
array(4) {
[0]=>
string(21) "d:\Scripts\script.php"
[1]=>
string(4) "arg1"
[2]=>
string(4) "arg2"
[3]=>
string(4) "arg3"
}

See $argv and $argc for further details.

To do what you want, lets say

php script.php arg1=4

You would need to explode the argument on the equals sign:-

list($key, $val) = explode('=', $argv[1]);
var_dump(array($key=>$val));

That way you can have whatever you want in front of the equals sign without having to parse it, just check the key=>value pairs are correct. However, that is all a bit of a waste, just instruct the user on the correct order to pass the arguments.

Passing a variable from BASH to PHP

You say in a comment that you are using php5-cgi to run the script.

php5-cgi is the CGI version of the interpreter; its purpose is to be used by the web server.

If you want to run the script on the command line then you have to use the CLI version of the interpreter. It's name is php (or, possibly, php5 on your system).

The CLI and CGI versions of the interpreter handle some things differently. The content of the variables $argc and $argv is one of these differences.

The CGI version populates them only if the register_argc_argv option is set to On (or 1) in php.ini. For performance reasons, this option is usually Off for the CGI.

On the other hand, the CLI version populates $argc and $argv variables with the parameters received in the command line no matter the value of register_argc_argv option.

As @andlrc also notes in their answer, you should enclose $1 in double quotes when you construct the command line in the shell script, to prevent the shell splitting it into words:

php /var/www/html/wave/waveform.php "$1"

If, for example, the value of $1 is foo bar (two words), your original usage renders to php waveform.php foo bar and print_r($argv) displays:

Array
(
[0] => waveform.php
[1] => foo
[2] => bar
)

On the other hand, if you enclose $1 in quotes, the command line becomes php waveform.php "foo bar" and the shell passes foo bar as a single argument to the PHP script. A print_r($argv) outputs:

Array
(
[0] => waveform.php
[1] => foo bar
)

As a side note, there is a missing { in copy($mp3, "$tmpname}_0.mp3");. It should probably read "copy($mp3, "${tmpname}_0.mp3");

PHP passing $_GET in the Linux command prompt

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.

How can I pass parameters from the command line to $_POST in a PHP script?

That's not easily doable. You can invoke the php-cgi binary and pipe a fake POST request in. But you'll need to set up a whole lot of CGI environment variables:

echo 'var1=123&var2=abc' | REQUEST_METHOD=POST  SCRIPT_FILENAME=script.php REDIRECT_STATUS=CGI CONTENT_TYPE=application/www-form-urlencoded php-cgi 

Note: Insufficient, doesn't work like that. But something like that...


It's certainly easier if you just patch the script, and let it load the $_POST array from a predefined environment variable.

$_POST = parse_url($_SERVER["_POST"]);

Then you can invoke it like _POST=var=123 php script.php for simplicity.

Send request parameters when calling a PHP script via command line

No, there is no easy way to achieve that. The web server will split up the request string and pass it into the PHP interpreter, who will then store it in the $_REQUEST array.

If you run from the command line and you want to accept similar parameters, you'll have to parse them yourself. The command line has completely different syntax for passing parameters than HTTP has. You might want to look into getopt.

For a brute force approach that doesn't take user error into account, you can try this snippet:

<?php
foreach( $argv as $argument ) {
if( $argument == $argv[ 0 ] ) continue;

$pair = explode( "=", $argument );
$variableName = substr( $pair[ 0 ], 2 );
$variableValue = $pair[ 1 ];
echo $variableName . " = " . $variableValue . "\n";
// Optionally store the variable in $_REQUEST
$_REQUEST[ $variableName ] = $variableValue;
}

Use it like this:

$ php test.php --param1=val1 --param2=val2
param1 = val1
param2 = val2


Related Topics



Leave a reply



Submit