PHP网络请求方法分析
一、分析php发送网网络请求的方法
在PHP中进行网络请求时,最常用的是CURL扩展,其次偶尔会使用file_get_contents函数。然而,file_get_contents仅能处理简单的网络交互,面对文件上传、Cookie管理、身份验证或表单提交等复杂场景则显得力不从心。相比之下,PHP的CURL能够模拟浏览器的行为,通过URL语法传输数据,因此它广泛支持FTP、FTPS、HTTP、HTTPS、GOPHER、TELNET、DICT、FILE以及LDAP等多种协议。此外,它还具备HTTPS认证、HTTP POST/PUT方法、FTP上传、Kerberos认证、代理服务器支持、Cookies处理、用户名/密码认证、断点续传(下载与上传)、HTTP代理管道、IPv6支持、SOCKS5代理以及通过HTTP代理向FTP服务器上传文件等高级功能。鉴于其强大的兼容性,建议在开发中优先选用CURL来处理各类网络请求,无论是简单还是复杂的任务。
二、file_get_contents发送网络请求示例
file_get_contents(path, include_path, context, start, max_length)

当使用file_get_contents、fopen、file或readfile等函数读取URL时,系统会自动创建一个名为$http_response_header的全局变量,用于保存HTTP响应的报头信息。若使用fopen等函数打开数据流,可以通过stream_get_meta_data函数获取该数据流的详细元数据信息。
$html = file_get_contents('http://www.baidu.com');
print_r($http_response_header);
$fp = fopen('http://www.baidu.com', 'r');
print_r(stream_get_meta_data($fp));
fclose($fp);
模拟POST请求:
$url = 'http://192.168.1.1/test.php';
$data = array(
'keyword' => 'test data',
);
$content = http_build_query($data);
$content_length = strlen($content);
$options = array(
'http' => array(
'method' => 'POST',
'header' =>
"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-length: $content_length\r\n",
'content' => $content
)
);
echo file_get_contents($url, false, stream_context_create($options));
三、php 用curl发送网络请求
CURL支持HTTPS认证、HTTP POST、FTP上传、代理、Cookies及简单口令认证等功能。在使用前,需确保PHP环境中已安装并启用了CURL模块。以下提供两种常见的写法供参考:
<?php
function geturl($url){
$headerArray =array("Content-type:application/json;","Accept:application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output,true);
return $output;
}
function posturl($url,$data){
$data = json_encode($data);
$headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return json_decode($output,true);
}
function puturl($url,$data){
$data = json_encode($data);
$ch = curl_init(); //初始化CURL句柄
curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output,true);
}
function delurl($url,$data){
$data = json_encode($data);
$ch = curl_init();
curl_setopt ($ch,CURLOPT_URL,$put_url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output,true);
}
function patchurl($url,$data){
$data = json_encode($data);
$ch = curl_init();
curl_setopt ($ch,CURLOPT_URL,$url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data); //20170611修改接口,用/id的方式传递,直接写在url中了
$output = curl_exec($ch);
curl_close($ch);
$output = json_decode($output);
return $output;
}
?>
一个函数片时各种请求:
function sendCurl($url, $data = null,$method='POST')
{
$method=strtoupper($method);
$start_wdmcurl_time = microtime(true);
$header = array(' application/x-www-form-urlencoded');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
// https 请求
if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
{
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
if($method=='GET'){
if($data && is_array($data) && count($data)>0 ){
$url.="?".http_build_query($data);
}
curl_setopt($ch, CURLOPT_URL, $url);
}elseif($method=='POST'){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
if (is_array($data) && count($data)>0)
{
curl_setopt($ch, CURLOPT_POST, true);
$isPostMultipart = false;
foreach ($data as $k => $v)
{
if ('@' == substr($v, 0, 1))
{
$isPostMultipart = true;
break;
}
}
unset($k, $v);
if ($isPostMultipart) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
}
}elseif(in_array($method,['PUT','DELETE','PATCH'])){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
$reponse = curl_exec($ch);
curl_close($ch);
return $reponse;
}
四、使用php composer的扩展guzzlehttp
composer require guzzlehttp/guzzle
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
在日常开发中,建议优先使用方法三,即自定义CURL处理网络请求,或者使用Composer管理的GuzzleHTTP扩展库,后者集成起来也非常便捷。
以上就是PHP实现网络请求的方法总结的详细内容,更多关于PHP网络请求的资料请关注本站其它相关文章!