简体   繁体   English

在PHP上接受带有CURL的cookie

[英]Accept cookies with CURL on PHP

I'm trying to run a log in script over my Centos machine. 我正在尝试在Centos计算机上运行登录脚本。 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. 尽管该脚本可以在我的PC上完美运行(Windows上为XAMPP),但在我的Centos框中似乎不起作用。 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? 怎样将这些代码转移到Linux机器上的工作代码中? What part am I missing? 我缺少哪一部分? Thank you very much, 非常感谢你,

Regards. 问候。

Code was indeed perfect. 代码确实是完美的。 All was needed is to create the file and give it the proper permissions. 需要做的只是创建文件并给予适当的权限。 Inspired by Marc B. Thank you. 受到Marc B的启发。谢谢。

The problem is concerned with the path to your cookie storage file. 问题与您的Cookie存储文件的路径有关。 'cookies.txt' you using is a relative path. 您使用的'cookies.txt'相对路径。 Relative paths works fine with internal PHP functions/extensions such as Filesystem functions. 相对路径可与内部PHP函数/扩展名(例如文件系统函数)配合使用。 That's because they all have access to information about the current PHP script. 那是因为他们都可以访问有关当前PHP脚本的信息。 But this is not always true for external extensions such as CURL. 但这对于外部扩展(例如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. 在大多数情况下,他们不知道当前PHP脚本的位置(实际上取决于安装),导致相对路径(例如'cookies.txt' )的结果不起作用。

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+): 为了获得绝对路径,您可以使用魔术常数 __FILE____DIR__ (在PHP 5.3+中):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM