使用cUrl管理cookie



你好,我在尝试将cookie存储在txt文件中时遇到问题。my_cookies.txt是该文件的同一文件夹中的一个txt。

我想在登录之前和之后管理cookie,在这个例子中是facebook然后我想把cookie插入数据库,但首先我需要把它放在.txt或至少保存中

显然,电子邮件和密码不是那样的

<?php
/* STEP 2. define path of form_action */
$url = "https://facebook.com/login.php?login_attempt=1";
$email = "nn";
$password = "nn";
/* STEP 3. create a connection with curl, give post information and save cookies */
$handler = curl_init();
//insert in the handler the path
curl_setopt($handler, CURLOPT_URL, $url);
//insert in the handler parameters of post
curl_setopt($handler, CURLOPT_POSTFIELDS,'email='.urlencode($email).'&pass='.urlencode($password));
//insert in the handler option to allow sending post information
curl_setopt($handler, CURLOPT_POST,1);
curl_setopt($handler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, false);
//load and save cookies generates in temp file
curl_setopt($handler, CURLOPT_COOKIEJAR, "my_cookies.txt");
curl_setopt($handler, CURLOPT_COOKIEFILE, "my_cookies.txt");
//catch information
curl_setopt ($handler, CURLOPT_RETURNTRANSFER, true);
//define agent
curl_setopt($handler, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0");
$response = curl_exec ($handler);
curl_close($handler);
echo $response; 
?>

谢谢你的帮助=),我希望你能做任何事情来帮助我:(

facebook提供了一个API,它比使用curl随机访问facebook页面更不容易出错

为了回答您的实际问题,尽管这是您正在寻找的功能它将文件读取到一个变量中,然后可以存储

PHP 5.3+

curl_setopt($handler, CURLOPT_COOKIEJAR, __DIR__."/my_cookies.txt");
curl_setopt($handler, CURLOPT_COOKIEFILE, __DIR__."/my_cookies.txt");

PHP 5.2-

curl_setopt($handler, CURLOPT_COOKIEJAR, dirname(__FILE__)."/my_cookies.txt");
curl_setopt($handler, CURLOPT_COOKIEFILE, dirname(__FILE__)."/my_cookies.txt");

还对文件使用绝对路径__DIR__给你力量

您可以将cookie分配给$cookies变量并就地使用它,

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);

然后在cURL过程中完成cookie的工作之后。您可以对该变量($cookies)执行任意操作。

提示:

  1. 为了存储到.txt中,您可以用__FILE__来存储相同的目录,或者用更多的路径附加__FILE__来存储在另一个目录中
  2. 您可以使用md5($_SERVER['REMOTE_ADDR'])生成Separate use.txt
  3. 对于存储到数据库中,INSERT命令将是可以的

最新更新