我有一个PHP脚本,登录到一个网站curl。当我在浏览器中运行脚本时,脚本可以正常登录。当我通过cronjob运行它时,它没有登录,因为cookie没有存储在我期望的位置。
如何存储cookie ?
这是脚本的相关部分。在此之前,定义了URL ($ URL)和登录数据($postrongtring)。
class curl {
function __construct($use = 1) {
$this->ch = curl_init();
if($use = 1) {
curl_setopt ($this->ch, CURLOPT_POST, 1);
curl_setopt ($this->ch, CURLOPT_COOKIEJAR, $_SERVER['DOCUMENT_ROOT'].'/verwaltung/cookie.txt');
curl_setopt ($this->ch, CURLOPT_COOKIEFILE, $_SERVER['DOCUMENT_ROOT'].'/verwaltung/cookie.txt');
curl_setopt ($this->ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($this->ch, CURLOPT_RETURNTRANSFER, 1);
} else {
return 'There is the possibility, that this script wont work';
}
}
function first_connect($loginform,$logindata) {
curl_setopt($this->ch, CURLOPT_URL, $loginform);
curl_setopt ($this->ch, CURLOPT_POSTFIELDS, $logindata);
}
function store() {
$store = curl_exec ($this->ch);
}
function execute($page) {
curl_setopt($this->ch, CURLOPT_URL, $page);
$this->content = curl_exec ($this->ch);
}
function close() {
curl_close ($this->ch);
}
function __toString() {
return $this->content;
}
}
$getit = new curl();
$getit->first_connect($url, $post_string);
$getit->store();
$getit->execute($url);
$getit->close();
经过编辑的问题反映了Wrikken和Colin Morelli的评论。谢谢你们两位!
从命令行运行脚本时,$_SERVER['DOCUMENT_ROOT']
变量将为空(毕竟,没有服务器,也没有文档根)。
这意味着$_SERVER['DOCUMENT_ROOT'].'/verwaltung/cookie.txt'
最终将解析为'/verwaltung/cookie.txt'
(和一个PHP通知)。这个目录可能不存在(它直接在根文件系统中;除了默认的Unix系统目录之外,不应该有任何东西),并且您的脚本将无法创建cookie文件(随后,不会保存cURL设置的任何cookie)。
代替$_SERVER['DOCUMENT_ROOT']
,您可以使用.
(当前目录),/tmp
(应该是所有用户都可以写的-而且也是可读的,小心!),__DIR__
(PHP脚本驻留的目录)或任何其他您自行决定的不依赖于服务器变量的目录。