pass parameters to php with shell

前端 未结 2 1678
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 17:35

my question is probably easy to answer. i want to execute my php file with shell and pass parameters to it via shell example

php test.php parameter1 paramet         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 18:34

    Yes you can do it like that but you should reference the arguments from the $_SERVER['argv'] array. $_SERVER['argc'] will tell you how many args were received, should you want to use that as a first layer of validation to make sure a required number of args were input.

    To illustrate this, running the following script as args.php arg1 arg2 arg3:

    #!/usr/bin/php
    
    

    will output:

    array(4) {
      [0]=>
      string(8) "args.php"
      [1]=>
      string(4) "arg1"
      [2]=>
      string(4) "arg2"
      [3]=>
      string(4) "arg3"
    }
    

    Here is a practical example:

    In this example, we'll create a script (days.php) that outputs the number of days since a particular date. It will accept 3 parameters, the month, day, and year as numbers.

    #!/usr/bin/php
    
    

    Shell call:

    `$ ./days 11 17 1988` OR `php days.php 11 17 1988`
    

    Output:

    7699 days since 11/17/1988
    

    Hope this helps.

提交回复
热议问题