PHP SSL Curl: "Object Moved" 错误

10

我正在开发一个PHP脚本来爬取这个网站的数据并将其发送到我的电子邮件中。看起来它已经成功登录了,因为当脚本运行时,它似乎会重定向并给我一个消息,说对象已移动到此处,这里链接到default.aspx页面,这与我手动登录时发生的情况完全相同。

以下是我的脚本:

<?php
$useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";

// INIT CURL
$ch = curl_init();

//init curl 
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'https://access.manager.com/Login.aspx');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

// Set your login and password for authentication
curl_setopt($ch, CURLOPT_USERPWD, 'testu:passwd');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);


// This is occassionally required to stop CURL from verifying the peer's certificate.
// CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if
// CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2 - check the existence of a
// common name and also verify that it matches the hostname provided)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Optional: Return the result instead of printing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'Username=testu&Password=passwd');

# Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
# not to print out the results of its query.
# Instead, it will return the results as a string return value
# from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

// EXECUTE 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);
echo $store;
// CLOSE CURL
curl_close ($ch);

?>

有没有什么想法可以解决页面无法正确输出的问题?我猜测可能是重定向出现了问题。

提前感谢。

2个回答

16
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

将其更改为1。另外,在CURLOPT_SSL_VERIFYPEER之后设置此项:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

另外,还要看一下CURLOPT_MAXREDIRS,你可能将来需要使用它。 - Alix Axel
1
为什么?为什么用户需要添加/更改这些内容? - The Codesee

3
你可以使用以下内容:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_MAXREDIRS,5); // return into a variable

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接