搜索
首页后端开发php教程PHP实现curl或file_get_contents 获取需要授权页面的方法

本篇文章主要介绍PHP实现curl或file_get_contents 获取需要授权页面的方法,感兴趣的朋友参考下,希望对大家有所帮助。

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

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

使用curl获取server.php页面

<?php 
$url = &#39;http://localhost/server.php&#39;; 
$param = array(&#39;content&#39;=>&#39;fdipzone blog&#39;); 
$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[&#39;http_code&#39;]==200){ 
 $data = json_decode($ret, true); 
 print_r($data); 
}else{ 
 echo &#39;POST Fail&#39;; 
} 
?>

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

<?php 
$url = &#39;http://localhost/server.php&#39;; 
$param = array(&#39;content&#39;=>&#39;fdipzone blog&#39;); 

$opt = array( 
 &#39;http&#39; => array( 
  &#39;method&#39; => &#39;POST&#39;, 
  &#39;header&#39; => &#39;content-type:application/x-www-form-urlencoded&#39;, 
  &#39;content&#39; => 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 &#39;POST Fail&#39;; 
} 
?>

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

Array 
( 
 [content] => fdipzone blog 
)

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

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

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

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

设定帐号:fdipzone 密码:654321

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

curl_setopt($ch, CURLOPT_USERPWD, '帐号:密码'); 

curl请求的程序修改为:

<?php 
$url = &#39;http://localhost/server.php&#39;; 
$param = array(&#39;content&#39;=>&#39;fdipzone blog&#39;); 

$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, &#39;fdipzone:654321&#39;); // 加入这句 
$ret = curl_exec($ch); 
$retinfo = curl_getinfo($ch); 
curl_close($ch); 
if($retinfo[&#39;http_code&#39;]==200){ 
 $data = json_decode($ret, true); 
 print_r($data); 
}else{ 
 echo &#39;POST Fail&#39;; 
} 
?>

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

file_get_contents 请求的程序修改为:

<?php 
$url = &#39;http://localhost/server.php&#39;; 
$param = array(&#39;content&#39;=>&#39;fdipzone blog&#39;); 

$auth = sprintf(&#39;Authorization: Basic %s&#39;, base64_encode(&#39;fdipzone:654321&#39;)); // 加入这句 

$opt = array( 
 &#39;http&#39; => array( 
  &#39;method&#39; => &#39;POST&#39;, 
  &#39;header&#39; => "content-type:application/x-www-form-urlencoded\r\n".$auth."\r\n", // 把$auth加入到header 
  &#39;content&#39; => 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 &#39;POST Fail&#39;; 
} 
?>

相关推荐:

PHP中file_put_contents函数详解

PHP使用file_get_contents发送http请求步骤详解

file_get_contents函数介绍与使用方法详解

以上是PHP实现curl或file_get_contents 获取需要授权页面的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何使PHP应用程序更快如何使PHP应用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,关注台词:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能优化清单:立即提高速度PHP性能优化清单:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,关注台词:1)启用opcodeCachingwithapCutoredUcescriptexecutiontime.2)实现databasequerycachingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandredececonnection.4 limitsclection.4.4

PHP依赖注入:提高代码可检验性PHP依赖注入:提高代码可检验性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显着提升了PHP代码的可测试性。 1)DI解耦类与具体实现,使测试和维护更灵活。 2)三种类型中,构造函数注入明确表达依赖,保持状态一致。 3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能优化:数据库查询优化PHP性能优化:数据库查询优化May 12, 2025 am 12:02 AM

databasequeryOptimizationinphpinvolVolVOLVESEVERSEVERSTRATEMIESOENHANCEPERANCE.1)SELECTONLYNLYNESSERSAYCOLUMNSTORMONTOUMTOUNSOUDSATATATATATATATATATATRANSFER.3)

简单指南:带有PHP脚本的电子邮件发送简单指南:带有PHP脚本的电子邮件发送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函数andsupportiveLibrariesLikePhpMailerandSwiftMailer.1)usethemail()functionforbasicemails,butithasimails.2)butithasimimitations.2)

PHP性能:识别和修复瓶颈PHP性能:识别和修复瓶颈May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显着提升PHP应用的性能。

PHP的依赖注入:快速摘要PHP的依赖注入:快速摘要May 11, 2025 am 12:09 AM

依赖性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增强量产生性,可验证性和Maintainability.itallowspasspassingDepentenciesLikEdenceSeconnectionSeconnectionStoclasseconnectionStoclasseSasasasasareTers,interitationApertatingAeseritatingEaseTestingEasingEaseTeStingEasingAndScalability。

提高PHP性能:缓存策略和技术提高PHP性能:缓存策略和技术May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具