Accept cookies with CURL on PHP

て烟熏妆下的殇ゞ 提交于 2021-01-28 11:40:33

问题


I'm trying to run a log in script over my Centos machine. What the script does is logging in with a username and password to a 3rd party site and gets the page contents.

Although the script works perfectly in my PC (XAMPP at Windows), in my Centos box it seems not work. After logging in, it keeps redirecting to the log in page (although the log in succeed). Here is the code:

function request($url,$post)
{
$ch = curl_init();
$curlConfig = array(
    CURLOPT_URL            => $url,
    CURLOPT_POST           => 1,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_COOKIEFILE => 'cookies.txt',
    CURLOPT_COOKIEJAR => 'cookies.txt',
    CURLOPT_USERAGENT => '"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"',
    CURLOPT_FOLLOWLOCATION => 1,
    CURLOPT_REFERER => $url,
    CURLOPT_POSTFIELDS     => $post
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
echo request('site.com/login.php',array("username" => "test", "password" => "test", "submit" => ""));

How would this code could be transfered to a working code in a Linux machine? What part am I missing? Thank you very much,

Regards.


回答1:


Code was indeed perfect. All was needed is to create the file and give it the proper permissions. Inspired by Marc B. Thank you.




回答2:


The problem is concerned with the path to your cookie storage file. 'cookies.txt' you using is a relative path. Relative paths works fine with internal PHP functions/extensions such as Filesystem functions. That's because they all have access to information about the current PHP script. But this is not always true for external extensions such as CURL. In most cases they doesn't know the location of the current PHP script (actually it depends on its installation) which results to relative paths (such as 'cookies.txt') doesn't work.

So the only way to ensure a path will work is to use absolute path. In order to obtain absolute path you can use magic constant __FILE__ or __DIR__ (in PHP 5.3+):

$curlConfig = array(
    ...
    CURLOPT_COOKIEFILE => dirname(__FILE__). '/cookies.txt',
    CURLOPT_COOKIEJAR => dirname(__FILE__). '/cookies.txt',
    ...
);


来源:https://stackoverflow.com/questions/26225462/accept-cookies-with-curl-on-php

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