PHP脚本从命令提示符-是否可以设置 read cookie


PHP script from command prompt - is it possible to set read cookies?

我有一个简单的php页面,我试图从终端控制台(ssh)运行这个php脚本:

php /home/account/domains/domain.com/public_html/script.php

现在,我可以运行脚本,问题是,如果我从控制台运行php脚本,设置'读取cookie不起作用,如果我从浏览器运行相同的页面,一切工作正常(读取和写入cookie ..)

所以我的问题是,我可以从终端运行这个脚本(就像上面一样),并使cookie以某种方式保存吗?

我的php脚本很简单:

setcookie("cookie", "cookie", time()+30);
if (!isset($_COOKIE["cookie"])){
echo "New Cookie is set!";
}else{
echo "The Cookie already set!";
}

非常感谢您的帮助!

cookie只存在于浏览器中。当您从命令行运行脚本时,不涉及浏览器,因此没有地方存储这些cookie。

如果您需要在调用命令行脚本时存储数据,则需要将其读写到文件中。一种简单的方法是:

// At the start of the script...
$PERSIST = unserialize(file_get_contents("myscript.cache")) ?: array();
// Read data from there...
print $PERSIST["blah"];
// Write some
$PERSIST["foo"] = "stuff";
// At the end of the script, save it back
file_put_contents("myscript.cache", serialize($PERSIST));

如果您愿意运行一些exec()函数,您可以保存cookie和其他东西-参见

如何通过Wget登录页面?