登录后cURL POST请求

时间:2014-07-09 14:41:54

标签: php cookies curl

我需要从需要身份验证的页面获取内容,之后需要为搜索标准创建发布请求。我以为我需要两个cURL请求:首先登录并保存会话数据,然后再提交表单...我尝试了几个变种。现有代码可以登录并获取内容,但只能提交在提交搜索表单之前的内容。而且它也不能使用我保存的会话,而我的cookie.txt文件不是空的。第二个cURL请求说它需要再次进行身份验证... 我的代码:

    $host       = 'http://mydomain.ee/search/?&page=1';
    $username   = 'myusername';
    $password   = 'mypassword';
    $data       = array('tel' => 3, 'ok' => 'Otsi');

    $curlHandler = curl_init($host);
    curl_setopt($curlHandler, CURLOPT_HEADER, 1);
    curl_setopt($curlHandler, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30);
    curl_setopt($curlHandler, CURLOPT_POST, 1);
    curl_setopt($curlHandler, CURLOPT_POSTFIELDS, "tel=3");
    curl_setopt($curlHandler, CURLOPT_POSTFIELDS, "ok=Otsi");
    curl_setopt($curlHandler, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($curlHandler, CURL_VERBOSE, TRUE);
    curl_setopt($curlHandler, CURLOPT_COOKIESESSION, TRUE);
    curl_setopt($curlHandler, CURLOPT_COOKIEJAR, $this->files_path . 'cookie.txt');
    curl_setopt($curlHandler, CURLOPT_COOKIEFILE, $this->files_path . 'cookie.txt');

    $return = curl_exec($curlHandler);

    curl_close($curlHandler);
    print_r(htmlspecialchars($return));
    echo '<br/><br/>';

    $curlHandler = curl_init($host);
    curl_setopt($curlHandler, CURLOPT_HEADER, 1);
    //curl_setopt($curlHandler, CURLOPT_USERPWD, $username . ":" . $password);
    curl_setopt($curlHandler, CURLOPT_TIMEOUT, 30);
    curl_setopt($curlHandler, CURLOPT_POST, 2);
    //curl_setopt($curlHandler, CURLOPT_POSTFIELDS, "tel=3");
    //curl_setopt($curlHandler, CURLOPT_POSTFIELDS, "ok=Otsi");
    curl_setopt($curlHandler, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $post);
    curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($curlHandler, CURL_VERBOSE, TRUE);
    curl_setopt($curlHandler, CURLOPT_COOKIESESSION, TRUE);
    //curl_setopt($curlHandler, CURLOPT_COOKIEJAR, $this->files_path . 'cookie.txt');
    curl_setopt($curlHandler, CURLOPT_COOKIEFILE, $this->files_path . 'cookie.txt');

    $return = curl_exec($curlHandler);

    curl_close($curlHandler);
    print_r(htmlspecialchars($return));

就像我说的:我在第一次curl_exec($ curlHandler)之后获得了html内容;但在第二次我得到: HTTP / 1.1 401授权要求日期:2014年7月9日星期三14:19:20 GMT服务器:Apache / 2 WWW-认证:基本领域=&#34;密码&#34;内容长度:18内容类型:text / html; charset = iso-8859-1未经授权(401) 为什么它不能使用它的cookie,filepath是一样的,cooki.txt有它的内容......如何修复它?

感谢您的帮助!

0 个答案:

没有答案