I have created a crontab rule:
* * * * * php /my/directory/file.php
I want to pass a variable to be used in the file.php from this crontab.
What is the best method to do this?
Bear in mind that running PHP from the shell is completely different from running it in a web server environment. If you haven't done command-line programming before, you may run into some surprises.
That said, the usual way to pass information into a command is by putting it on the command line. If you do this:
php /my/directory/file.php "some value" "some other value"
Then inside your script, $argv[1]
will be set to "some value"
and $argv[2]
will be set to "some other value"
. ($argv[0]
will be set to "/my/directory/file.php"
).
When you execute a PHP script from command line, you can access the variable count from $argc
and the actual values in the array $argv
. A simple example.
Consider test.php
<?php
printf("%d arguments given:\n", $argc);
print_r($argv);
Executing this using php test.php a b c
:
4 arguments given:
Array
(
[0] => test.php
[1] => a
[2] => b
[3] => c
)
May I add to the $argv
answers that for more sophisticated command-line parameters handling you might want to use getopt()
: http://www.php.net/manual/en/function.getopt.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With