0

I am calling a PHP script from bash and occasionally I will supply it 2 or sometimes 3 parameters like so

Bash script

 ip =  192.168.1.4
 name = machine2
 callScript=`/usr/bin/php check.php $ip $name`
 callScript2=`/usr/bin/php check.php $name`

As you can see, on one occasion I call the PHP script with two parameters, and on another with one parameter. The problem begins with the second, because PHP has argv[1] and argv[2] and then PHP complains stating PHP Notice: Undefined offset: 2 because no second parameter was passed

Here is my PHP script

$placeholder = NULL;
if ($argv[2] === NULL) {
   //Do nothing
} else {
   $placeholder = $argv[2];
}

I am doing this so that if a second parameter is passed, store it in the placeholder, but if not don't do anything. The problem is PHP stops right on the second line of my code because $argv[2] does not exist as I only supply it one parameter on occasion.

whatitis2
  • 137
  • 1
  • 3
  • 2
    Test `$argc` to see how many parameters are passed `if ( $argc==2){` or `if ($argc==3){` – RiggsFolly Apr 16 '19 at 16:43
  • If I try that, PHP still complains about the last line where I am doing $placeholder = $argv[2]; stating undefined offset 2 – whatitis2 Apr 16 '19 at 16:45
  • See https://www.php.net/manual/en/reserved.variables.argc.php – RiggsFolly Apr 16 '19 at 16:45
  • 1
    Then you are not testing it correctly. Remember `$argv[0]` will always be the name of the script being called `$argv[1]` will be first parameter etc etc – RiggsFolly Apr 16 '19 at 16:46
  • Your shell script has obvious syntax errors. You should probably get used to checking with http://shellcheck.net/. Also the backticks look suspicious, it's hard to say without more context if they are actually wrong but needless backticks seems to be a common error among PHP programmers. – tripleee Apr 16 '19 at 18:29

1 Answers1

0

Check to see if it is set rather than null.

$placeholder = (isset($argv[2]) ? $argv[2] : null);
Dave
  • 5,108
  • 16
  • 30
  • 40