在PHP cURL帮助中传递凭据

时间:2011-06-08 14:39:20

标签: php curl libcurl

我正在尝试将凭据传递到网站,以便我可以使用file_get_contents来提取一些数据,但它不起作用,我得到一个空白页面,所以任何想法在这里有什么问题?

<?php


$username="munged@ring.gil.com";
$password="Koin";

$url="confluence.rogersdigitalmedia.com";


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

$str= file_get_contents("confluence.rogersdigitalmedia.com/display/prodsupport/Team+Calendar");
echo $str;
?>

当我获取内容时,以下是新代码仍无法在登录界面停留.... screenshot

<?php
$username="munged@gil.ro.com";
$password="Koin";

$url="confluence.rogersdigitalmedia.com";


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


//Replaced due to special chars in url for username and pass
//curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_USERPWD, urlencode($username) . ':' . urlencode($password));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

echo file_get_contents('http://confluence.rogersdigitalmedia.com/exportword?pageId=1114407');
?>

新代码:我知道$url是我必须登录的网址,但我在$data放了什么?我知道这是我的登录信息,但我该怎么做呢(例如&lt; username&gt; space&lt; password&gt;)?

<?php
function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

1 个答案:

答案 0 :(得分:4)

您可能需要转义用户名中的@

curl_setopt($ch, CURLOPT_USERPWD, urlencode($username) . ':' . urlencode($password));

这是因为某些字符(例如@:)在网址中具有特殊含义。您需要转义它们,以便服务器将它们视为字符,而不是指示有关HTTP请求的内容。

废弃所有这些。您的编辑显示您对HTTP的工作方式存在根本的误解。您不能使用CURL将HTTP登录凭据传递给希望填写Web表单然后希望能够使用file_get_contents(这是完全独立的API的一部分)登录的站点。< / p>

就实际操作方式而言......首先,找出网站是否有API。如果没有,请确定他们是否真的希望您进行屏幕抓取。屏幕抓取不允许它的网站将是非常糟糕的形式。事实上,它可能违反了版权法。

其次,编程到API。这意味着以网站强制执行的方式登录。这将是表单值(您可能需要在CURLOPT_POSTFIELDS中发送)和cookie(您需要在每个请求中使用,可能使用CURLOPT_COOKIEFILE)。

了解客户端 - 服务器关系如何工作,研究API,不要只是查看问题的代码并期望它能够正常工作。