Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass crontab a variable and read it from PHP?

Tags:

php

cron

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?

like image 448
Hesham Saeed Avatar asked Apr 22 '12 00:04

Hesham Saeed


3 Answers

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").

like image 135
Mark Reed Avatar answered Oct 14 '22 14:10

Mark Reed


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
)
like image 7
kba Avatar answered Oct 14 '22 16:10

kba


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

like image 1
lafor Avatar answered Oct 14 '22 16:10

lafor