原文:http://blog.csdn.net/fdipzone/article/details/44475801

红色字体部分是加上自己的注释,整理了一下。

今天因工作需要,需要用 curl / file_get_contents 获取需要授权(Authorization)的页面内容,解决后写了这篇文章分享给大家

php curl 扩展,能够在服务器端发起POST/GET请求,访问页面,并能获取页面的返回数据。

例如要获取的页面:http://localhost/server.php

<?php
$content = isset($_POST['content'])? $_POST['content'] : '';
header('content-type:application/json');
echo json_encode(array('content'=>$content));
?>

使用curl获取server.php页面

<?php
$url = 'http://localhost/server.php';
$param = array('content'=>'fdipzone blog'); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($ch);
$retinfo = curl_getinfo($ch);
curl_close($ch); if($retinfo['http_code']==200){
$data = json_decode($ret, true);
print_r($data);
}else{
echo 'POST Fail';
}
?>

如果服务没有安装php curl扩展,使用file_get_contents也可以实现发起请求,获取页面返回数据

<?php
$url = 'http://localhost/server.php';
$param = array('content'=>'fdipzone blog'); $opt = array(
'http' => array(
'method' => 'POST',
'header' => 'content-type:application/x-www-form-urlencoded',
'content' => http_build_query($param)
)
); $context = stream_context_create($opt); $ret = file_get_contents($url, false, $context); if($ret){
$data = json_decode($ret, true);
print_r($data);
}else{
echo 'POST Fail';
}
?>

使用curl 和 file_get_contents 返回的结果都是一样的。

Array
(
[content] => fdipzone blog
)

对于需要授权的页面,例如使用了htpasswd+.htaccess设置目录访问权限的页面,直接用上面的方法会返回401 Unauthorized错误。

这次的例子先不使用htpasswd+.htaccess来控制访问权限,而使用
$_SERVER['PHP_AUTH_USER'] 和
$_SERVER['PHP_AUTH_PW']这两个服务器参数。

使用$_SERVER参数的方式更简单,省去了修改配置文件和生成密码文件的烦恼,只要返回头header('WWW-Authenticate: Basic realm="localhost"');就可以达到登录框弹出的效果。

如果想使用配置文件的方式:

htpasswd+.htaccess方式的配置看我另一篇博客:http://www.cnblogs.com/leezhxing/p/3298060.html

nginx配置http auth看网上的一篇博客:http://blog.slogra.com/post-140.html

http://localhost/server.php 修改为:

<?php
if(!isset($_SERVER['PHP_AUTH_USER']))
{
header('WWW-Authenticate: Basic realm="localhost"');
header("HTTP/1.0 401 Unauthorized");
exit;
}else{
if (($_SERVER['PHP_AUTH_USER']!= "fdipzone" || $_SERVER['PHP_AUTH_PW']!="654321")) {
header('WWW-Authenticate: Basic realm="localhost"');
header("HTTP/1.0 401 Unauthorized");
exit;
}
} $content = isset($_POST['content'])? $_POST['content'] : '';
header('content-type:application/json');
echo json_encode(array('content'=>$content));
?>

设定帐号:fdipzone 密码:654321

curl中,有一个参数是 CURLOPT_USERPWD,我们可以利用这个参数把帐号密码在请求时发送过去。

<?php
$url = 'http://localhost/server.php';
$param = array('content'=>'fdipzone blog'); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, 'fdipzone:654321'); // 加入这句
$ret = curl_exec($ch);
$retinfo = curl_getinfo($ch);
curl_close($ch); if($retinfo['http_code']==200){
$data = json_decode($ret, true);
print_r($data);
}else{
echo 'POST Fail';
}
?>

而file_get_contents 如果要发送帐号和密码,需要手动拼接header

file_get_contents 请求的程序修改为:

<?php
$url = 'http://localhost/server.php';
$param = array('content'=>'fdipzone blog'); $auth = sprintf('Authorization: Basic %s', base64_encode('fdipzone:654321')); // 加入这句 $opt = array(
'http' => array(
'method' => 'POST',
'header' => "content-type:application/x-www-form-urlencoded\r\n".$auth."\r\n", // 把$auth加入到header
'content' => http_build_query($param)
)
); $context = stream_context_create($opt); $ret = file_get_contents($url, false, $context); if($ret){
$data = json_decode($ret, true);
print_r($data);
}else{
echo 'POST Fail';
}
?>

curl 或 file_get_contents 获取需要授权页面的方法的更多相关文章

  1. curl 要么 file_get_contents 获得授权页面的方法的必要性

    今天,需要工作,需要使用 curl / file_get_contents 获得授权的必要性(Authorization)的页面内容.解决后写了这篇文章分享给大家. php curl 扩展,可以在se ...

  2. PHP CURL或file_get_contents获取网页标题的代码及两者效率的稳定性问题

    PHP CURL与file_get_contents函数都可以获取远程服务器上的文件保存到本地,但在性能上面两者完全不在同一个级别,下面我先来介绍PHP CURL或file_get_contents函 ...

  3. 解析PHP中的file_get_contents获取远程页面乱码的问题【转】

    在工作中,遇到一个问题.我需要将一个网址(该网址是一个json数据的接口,即 打开该网址,在浏览器中显示的是json数据),我使用file_get_contents($url),数据是乱码的. 通过查 ...

  4. Chrome获取微信授权,调试公众号页面

    1.目的 你可能遇到过这种情况,在微信中打开公众号是这样的. 复制链接,在chrome中打开是这样的. 博主今天要解决的就是,如果在chrome中加载需要微信授权的页面,至于加载成功后要干嘛,测试?抓 ...

  5. OAuth2.0 微博登陆网站功能的实现(一)获取用户授权及令牌 Access Token

    在登陆一些网站的时候,可以选择登陆方式为第三方登陆,例如微博登陆,以爱奇艺为例,进入首页,点击 ”登陆“,会弹出登录框: 除了本站登陆外,还可以选择其他第三方登陆,比如微博登陆.QQ 登陆.微信登陆等 ...

  6. PHPsocket、CURL、File_get_contents采集

    1.socket采集.采用最底层的,它只是建立一个长连接,然后我们自己构造http协议字符串去发送请求.例如想获取这个页面内容(http://tv.youku.com/?spm=a2hww.20023 ...

  7. PHP使用curl替代file_get_contents

    初学php的朋友们,很容易翻一个错误,在写采集程序或者调用api接口总会有线考虑到使用file_get_contents函数来或许内容,程序的访问量不大倒是没什么影响,但是访问量提升了那非常的悲剧了, ...

  8. file_get_contents 获取不了网页内容

    服务器在做验签的过程中,经常需要向渠道服务器获取某个用户的信息.一般有两种方法,curl和file_get_contents. 一般情况下,像这样用,不会有问题. public function Oa ...

  9. 远程读取URL 建议用curl代替file_get_contents

    初学php的朋友们,很容易翻一个错误,在写采集程序或者调用api接口总会有线考虑到使用file_get_contents函数来或许内容,程序的访问量不大倒是没什么影响,但是访问量提升了那非常的悲剧了, ...

随机推荐

  1. hdu2665 && poj2104划分树

    K-th Number Time Limit: 20000MS   Memory Limit: 65536K Total Submissions: 47066   Accepted: 15743 Ca ...

  2. jquery的ajax提交form表单

    $.ajax({ cache: true, type: "POST", url:ajaxCallUrl, data:$('#yourformid').serialize(),// ...

  3. c#如何使输入数据类型限制,C#如何添加限制

    验证n位的数字:^\d{n}$ ,例如要输6位数字,不能多也不能少: ^\d{6}$ 验证数字的正则表达式集 验证数字:^[0-9]*$验证n位的数字:^\d{n}$验证至少n位数字:^\d{n,}$ ...

  4. PyCharm2016.23专业版注册码

    43B4A73YYJ-eyJsaWNlbnNlSWQiOiI0M0I0QTczWVlKIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXNzaWduZWVOYW1lIjoiI ...

  5. C# asp.net mvc 配置多个route 参数

    mvc 中路由可以自定义 public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { ...

  6. htm.dropdownlist

    @Html.DropDownList("status", new SelectList(new[] { "驳回", "确认", " ...

  7. 【随笔】mvc使用forms身份验证实现登陆

  8. 更改codeblocks的配色方案

    codeblocks默认只有一种配色方案, 不过我们可以手动添加. 在终端下输入如下命令: cd ~/.codeblocks sudo gedit default.conf 在打开的配置文件中, 找到 ...

  9. PHP Datatype Conversion Safety Risk、Floating Point Precision、Operator Security Risk、Safety Coding Principle

    catalog . 引言 . PHP operator introduction . 算术运算符 . 赋值运算符 . 位运算符 . 执行运算符 . 递增/递减运算符 . 数组运算符 . 类型运算符 . ...

  10. bash的配置

    Bash的启动文件 启动文件也是一种脚本,不过它是在Bash在启动之初就执行它的.不同的启动方式使用的启动文件也有不同. 1. 作为交互的登录脚本环境“交互的”是指你可以再这个环境下输入命令.而所谓的 ...