我正在尝试向需要登录的网站发出请求,但服务器不支持https协议,所以我不能使用curl。
我看到的原始代码如下:
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0',
CURLOPT_COOKIEJAR => dirname(__FILE__) . '\cookies.txt',
CURLOPT_COOKIEFILE => dirname(__FILE__) . '\cookies.txt',
CURLOPT_RETURNTRANSFER => 1
)
curl_setopt_array($ch, $options);
$page = curl_exec ($ch);
使用file_get_contents时,我想出了以下内容:
$cookies = file_get_contents(dirname(__FILE__) . '\cookies.txt');
$primary_context_options = array(
"http" => array(
"method" => "GET",
"follow_location" => true,
"header" => "Cookie: " . $cookies . "\r\n" .
"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0\r\n"
),
"ssl" => array(
"verify_peer" => false,
)
);
$primary_context = stream_context_create($primary_context_options);
$page = file_get_contents($url, false, $primary_context);
第一个请求返回正常,但我不确定我是否正确设置了cookie。 唯一的问题是我使用凭证登录的第二个请求:
$login_context_options = array(
"http" => array(
"method" => "POST",
"header" => "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($post) . "\r\n"
. "Referer: " . $url . "\r\n",
"content: " . $post
)
);
$login_context = stream_context_create($login_context_options);
$login = file_get_contents($login_url, false, $login_context);
它总是返回:
"file_get_contents($url_encoded_login_url_of_website) failed to open stream: HTTP request failed!"
我可以使用curl使用给定的URL正常登录,所以我不知道我在这里缺少什么。
如果有帮助,这是使用curl进行登录的原始代码:
$additional_options = array(
CURLOPT_URL => $login_url,
CURLOPT_REFERER => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post
);
curl_setopt_array($ch, $additional_options);
curl_exec($ch);
任何想法我可以用file_get_contents版本犯下什么错误?提前谢谢!