原文: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. 【UOJ #20】【NOIP 2014】解方程

    http://uoj.ac/problem/20 并不会做...然后看题解....... 对a取模,避免了高精度带来的复杂度,然后再枚举x判断是否满足模意义下等于0. 取5个模数,我直接抄的别人的_( ...

  2. mysql之旅【第二篇】

    创建,修改和删除表 1,创建表: create table 表名(属性名   数据类型   [完整性约束条件], 属性名   数据类型   [完整性约束条件], 属性名   数据类型   [完整性约束 ...

  3. org.apache.commons.lang3.ArrayUtils 学习笔记

    package com.nihaorz.model; /** * @作者 王睿 * @时间 2016-5-17 上午10:05:17 * */ public class Person { privat ...

  4. Ext-设置form表单不可编辑

    1. var formEach = win.down('form').items.items; Ext.each(formEach,function(item){ console.log(item); ...

  5. sql 定义自增id插入数据

    -- 定义一个自增变量 ; -- 执行自增语句 ,sponsorbroker,,, from stock_listing_detailed_info group by sponsorbroker;

  6. 【深入Java虚拟机】之二:Java垃圾回收机制

    [深入Java虚拟机]之:Java垃圾收集机制 对象引用 Java中的垃圾回收一般是在Java堆中进行,因为堆中几乎存放了Java中所有的对象实例.谈到Java堆中的垃圾回收,自然要谈到引用.在JDK ...

  7. Java中字符串的几个实例

    String str=new String("abc");new 对象时,位于堆中,同时看字符串常量中是否有字符串"abc",如果没有,则进行添加,同时进行关联 ...

  8. python学习笔记10(Python的内存管理)

      用这张图激励一下自己,身边也就只有一位全栈数据工程师!!! 32. Python的内存管理 1. 对象的内存使用 对于整型和短字符串对象,一般内存中只有一个存储,多次引用.其他的长字符串和其他对象 ...

  9. 【BZOJ-2962】序列操作 线段树 + 区间卷积

    2962: 序列操作 Time Limit: 50 Sec  Memory Limit: 256 MBSubmit: 678  Solved: 246[Submit][Status][Discuss] ...

  10. NetLink Communication Mechanism And Netlink Sourcecode Analysis

    catalog . Netlink简介 . Netlink Function API Howto . Generic Netlink HOWTO kernel API . RFC Linux Netl ...