0

我有一个使用 curl 登录网站的 PHP 脚本。当我在浏览器中运行脚本时,脚本可以正常登录。当我通过 cronjob 运行它时,它不会登录,因为 cookie 没有存储在我预期的位置。

如何存储 cookie?


这是脚本的相关部分。在此之前定义 URL ($url) 和登录数据 ($post_string)。

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 在下面的评论。谢谢你俩!

4

1 回答 1

0

从命令行运行脚本时,$_SERVER['DOCUMENT_ROOT']变量将为空(毕竟,没有服务器,也没有文档根目录)。

This means that $_SERVER['DOCUMENT_ROOT'].'/verwaltung/cookie.txt' will eventually resolve to '/verwaltung/cookie.txt' (and a PHP notice). This directory will probably not exist (it's directly in the root filesystem; there shouldn't be anything besides the default Unix system directories) and your script will not be able to create the cookie file (and subsequently, not save any cookies set by cURL).

Instead of $_SERVER['DOCUMENT_ROOT'], you could for example use . (the current directory), /tmp (should be writable by all users -- and also readable, be careful!), __DIR__ (the directory the PHP script resides in) or any other directory at your discretion that does not depend on server variables.

于 2013-03-06T20:46:57.017 回答