我正在使用php来刮WWW。需要会话才能登录的Example.com。我已经使用php curl成功登录了。 请检查此链接Keeping session alive with curl and php。现在在链接中显示如何使用相同的会话cookie发出第二个请求。
我的问题是当我刮
时define("COOKIE_FILE", "cookie.txt");
// Login the user
$ch = curl_init('http://api.example.com/login/joe/smith');
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
echo curl_exec ($ch);
// Read the session saved in the cookie file
echo "<br/><br/>";
$file = fopen("cookie.txt", 'r');
echo fread($file, 100000000);
echo "<br/><br/>";
// Get the users details
$ch = curl_init('http://api.example.com/user');
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
echo curl_exec ($ch);
我的代码是
define("COOKIE_FILE", "cookie.txt");
// Login the user
$ch = curl_init('http://api.example.com/login/joe/smith');
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
echo curl_exec ($ch);
// Read the session saved in the cookie file
echo "<br/><br/>";
$file = fopen("cookie.txt", 'r');
echo fread($file, 100000000);
echo "<br/><br/>";
// Get the users details
$ch = curl_init('http://api.example.com/user');
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username=abc&password=xyz&domain=123');
echo curl_exec ($ch);
输出
# Netscape HTTP Cookie File # https://curl.haxx.se/docs/http-cookies.html # This file was generated by libcurl! Edit at your own risk. www.example.com FALSE /unifyv3 FALSE 0 JSESSIONID 5366C3DB90DE7187A66E0BD19F595309
HTTP/1.1 200 OK Date: Fri, 05 Aug 2016 19:48:25 GMT Server: Apache/2.2.3 (CentOS) Set-Cookie: JSESSIONID=225D8E499DE23F0FDF454D73F0C05F25; Path=/unifyv3 Content-Length: 2850 Connection: close Content-Type: text/html;charset=UTF-8
Logout
Your session has expired
Click here to log in again
Redirecting to Login Page in secs.
当第二个请求是GET请求时,一切正常。在POST请求时,网站返回“您的会话已过期,请再次登录”。
如何解决这个问题?。我已经尝试了几种解决方案并在谷歌搜索,没有任何作用。最终决定发布在这里。提前谢谢。