Grant Grant - 1 year ago 59
PHP Question

Passing a variable from BASH to PHP

I've read all of the articles I could find on here on this and none of them seem to be working.

I'm using a bash script to fire a php script but I can't seem to get the variable into php...

Bash script where $1=mymusic.mp3

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


$mp3 = '/var/www/html/processed/' . $argv[1];
copy($mp3, "$tmpname}_0.mp3");

The $argv[1] variable is just not being received by php, any ideas?

Answer Source

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:

    [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:

    [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");