pass crontab a variable and read it from PHP?

后端 未结 4 2050
无人共我
无人共我 2021-01-05 01:22

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.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 01:36

    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.

提交回复
热议问题