hd. hd. - 7 months ago 25
PHP Question

Pass variable to php script running from command line

I have a php file that is needed to be run from command line (via crontab). but i need to pass 'type=daily' to the file but i don't know how.i tried

php myfile.php?type=daily

but this error was result:

Could not open input file: myfile.php?type=daily

what can i do?


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:

wget http://location.to/myfile.php?type=daily

or check in the php file wether it's called from the commandline 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)