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.
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:
global $argv;
echo "argv0: $argv[0]\n\r"; // echoes: argv0: /server/path/to/my/script/my-script.php
echo "argv1: $argv[1]\n\r"; // echoes: argv1: test.tst
echo "argv2: $argv[2]\n\r"; // echoes: argv2: folder=0
I got the same results with $_SERVER['argv']
superglobal array.
One can make use of it like this:
$myargv = $_SERVER['argv'];
echo $myargv[1]; // echoes: test.tst
Hope that helps somebody.
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"
).
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
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
)