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?
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:
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"
).May I add to the
$argv
answers that for more sophisticated command-line parameters handling you might want to usegetopt()
: http://www.php.net/manual/en/function.getopt.phpWhen 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
Executing this using
php test.php a b c
:Neither of the above methods worked for me. I run cron on my hoster's shared server. The cron task is created with the cPanel-like interface. The command line calls PHP passing it the script name and a couple arguments.
That is how the command line for cron looks:
php7.2 /server/path/to/my/script/my-script.php "test.tst" "folder=0"
Neither of the answers above with
$argv
worked for my case.The issue was noone told you have to declare
$argv
as global before you get the access to the CLI arguments. This is neither mentioned in the official PHP manual.Well, probably one has to declare
$argv
global ony for scripts run with server. Maybe in a local environment running script in CLI$argv
does not require being declared global. When I test it I post here.But nevertherless for my case the working configuration is:
I got the same results with
$_SERVER['argv']
superglobal array. One can make use of it like this:Hope that helps somebody.