远程登录并在PHP中使用cURL显示内容


Login Remotely and Display Content using cURL in PHP

我在PHP中使用cURL登录到我的远程服务器。我已成功登录远程URL,但似乎无法显示该页面的内容。这是我到目前为止的代码:

<?php
$username = 'Blah';
$password = 'BlahBlah';
$ch = curl_init();
$postdata="email=$username&password=$password";
curl_setopt ($ch, CURLOPT_URL,"http://www.example.com/login.php");
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, 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");
curl_setopt ($ch, CURLOPT_HEADER, true);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt ($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt ($ch, CURLOPT_REFERER, "http://www.example.com/login.php");
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/User/Home.php") ;
$result2 = curl_exec($ch) ;
echo $result2 ;
curl_close($ch);
?>

当我尝试回显$result2时,什么都没有。屏幕上没有打印任何内容。我需要做什么才能将内容打印到屏幕上?

以下是HTTP标头输出:

HTTP/1.1 302 Moved Temporarily Date: Sun, 26 May 2013 23:46:40 GMT Server: Apache/2.2.23 (Unix) mod_ssl/2.2.23 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Set-Cookie: current_page=Home.php; expires=Wed, 24-May-2023 23:46:40 GMT Location: http://www.example.com/?redirected=3 Vary: Accept-Encoding,User-Agent Content-Length: 0 Content-Type: text/html HTTP/1.1 200 OK Date: Sun, 26 May 2013 23:46:40 GMT Server: Apache/2.2.23 (Unix) mod_ssl/2.2.23 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Vary: Accept-Encoding,User-Agent Transfer-Encoding: chunked Content-Type: text/html

它可能没有遵循重定向。用途:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

PHP中有许多类型的值在echo'ed时不产生输出。在我的脑海中,这包括bool(false)NULL""(空振铃(。可能更多。为了查看它们之间的差异,请使用var_dump来区分所有它们$result2可能是emptystring或bool(false(,使用echo无法判断是哪一个。然而,考虑到http标头包含Content-Length: 0,它几乎肯定是空的。此外,$username和$password不是url编码的,因此如果它们包含application/x-www-urlencoded-格式的任何具有特殊含义的字符,服务器将收到错误的用户名/密码。这包括空间&=?和其他几个。它们需要进行url编码,就像$postdata='email='.urlencode($username).'&password='.urlencode($password);一样,另一件事是,在调试curl代码时,启用CURLOPT_VERBOSE,它会打印很多有用的调试信息。

但@Marshall House是正确的,服务器发送了一个HTTP/1.1 302 Moved Temporarily url重定向,希望你遵循。。。而你却没有。您可以使用CURLOPT_FOLLOWLOCATION告诉curl自动遵循http重定向。