Use Session in Cronjob (Crontab)

送分小仙女□ 提交于 2019-12-13 14:16:57

问题


Hi is it possible to use sessions in a cronjob?

The Script I use is:

session_start();

if(empty($_SESSION['startwert'])){$startwert = 0;}
else {$startwert = $_SESSION['startwert'];}

if(empty($_SESSION['zielwert'])){$zielwert = 10000;}
else {$zielwert = $_SESSION['zielwert'];}


....


$_SESSION['startwert'] = $zielwert;
$_SESSION['zielwert'] = $zielwert + 10000;
echo "Startwert: ".$_SESSION['startwert']."<br>";
echo "Zielwert: ".$_SESSION['zielwert']."<br>";

But the Cron allways start set "startwert" to 10000 and "zielwert" to 20000 and it does not increase the values.


Ok now I have tried this.

/usr/bin/wget -O - http://mydomain.com/script.php

But the cron starts allways with 10000 and 20000. Any ideas?


回答1:


If you're invoking the PHP script from cron via wget, use the --save-cookies option; if via curl, use --cookie-jar. (If you're invoking the PHP script via php -f [...] or similar, then you'll first need to invoke it via wget or curl instead.)

For example:

wget --load-cookies /tmp/cron-session-cookies --save-cookies /tmp/cron-session-cookies --keep-session-cookies [...]

or

curl -b --cookie-jar /tmp/cron-session-cookies [...]

wget by default doesn't save session cookies, which you want it to do, hence the --keep-session-cookies option; curl by default does save them, so all that's necessary is -b to enable cookies and --cookie-jar to tell curl where to find them. In either case, replace the [...] with whatever options and arguments you're already passing to the program, and adjust the location of the cookie jar file to taste.




回答2:


Not really. PHP sessions are dependent on cookies (ignoring trans-sid mode), which really only exist in an HTTP context. cron jobs are running in CLI mode, so there's no http layer to deal with.

You CAN force a CLI script to use a particular session file by setting the session ID before calling session_start();, but there's no guaranteed that particular ID would actually exist when the cron job starts, as some other PHP instance's session garbage collector may have deleted it.



来源:https://stackoverflow.com/questions/16797885/use-session-in-cronjob-crontab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!