I have a PHP file that is needed to be run from command line (via crontab). 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 returned:
Could not open input file: myfile.php?type=daily
What can I do?
Just pass it as normal parameters and access it in PHP using the
$argv
array.and in myfile.php
These lines will convert the arguments of a CLI call like
php myfile.php "type=daily&foo=bar"
into the well known$_GET
-array:Though it is rather messy to overwrite the global
$_GET
-array, it converts all your scripts quickly to accept CLI arguments.See http://php.net/manual/en/function.parse-str.php for details.
Save this code in file
myfile.php
and run asphp myfile.php type=daily
If you add
var_dump($b);
before the?>
tag, you will see that the array$b
containstype => daily
.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 bemyfile.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:
Or check in the php file whether it's called from the commandline or not:
(Note: You'll probably need/want to check if
$argv
actually contains enough variables and such)You could use what sep16 on php.net recommends:
It behaves exactly like you'd expect with cgi-php.
will set
$_GET['type']
to'daily'
,$_GET['a']
to'1'
and$_GET['b']
toarray('2', '3')
.Just pass it as parameters as follows:
and inside test.php: