本文作者:DurkBlue

php尝试发送接受GET与POST请求

DurkBlue 2019-12-16 1734 抢沙发
php尝试发送接受GET与POST请求摘要: 用 file_get_contents() 发送get请求,如果请求失败会返回 FALSE 。在发送请求是如果url有空格之类的特殊字符需要对url进...

用 file_get_contents() 发送get请求,如果请求失败会返回 FALSE 。在发送请求是如果url有空格之类的特殊字符需要对url进行urlencode进行编码,file_get_contents()除了可以进行get请求处理,还能发送post请求,同时也可以把文件读入一个字符串。在读取文件是性能高效。

    1.file_get_contents()发送get请求代码

<?php
    $url='http://www.zixuephp.net';      
    $content= file_get_contents($url);      
    if($content){  echo 'GET 请求发送成功!'; }
?>

    2.file_get_contents()发送post请求代码

php$url = 'zixuephp.net';//数据$data = array(    'param' => 'test',);//讲post请求数据生成 URL-encode 之后的请求字符串$content = http_build_query($data);//数据长度$content_length = strlen($content);//构造请求post头$options = array(    'http' => array(        'method' => 'POST',        'header' =>        "Content-type: application/x-www-form-urlencoded" .        "Content-length: $content_length",        'content' => $content    ));//执行请求,填入请求头信息if(file_get_contents($url, false, stream_context_create($options))){    echo 'post请求成功!';}

    3.解决file_get_contents()请求乱码问题:

        上面说完php通过file_get_contents()发送get和post请求,下面再说些关于file_get_content()抓取网页内容时乱码问题的解决。

        在实际测试中发现,网页中的gzip压缩导致file_get_content()请求返回数据乱码的情况,通过修改请求头中的设置可以解决乱码问题。

     把请求头中Accept-Encoding: gzip, deflate修改成Accept-Encoding: deflate解决乱码问题,如下设置代码:

php//请求头定义$opts = array(    'http'=>array(        'method'=>"GET",        'header'=>            "Host: zixuephp.net\r\n".            "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0\r\n".            "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n".            "Accept-Language: zh-CN,en-US;q=0.5\r\n".            "Accept-Encoding: deflate\r\n".            "Referer: http://zixuephp.net/".            "Cookie: PHPSESSID=equbccc5nf2ighirl7fbevrm86\r\n".            "Connection: keep-alive\r\n".            "Upgrade-Insecure-Requests: 1",        'timeout'=>5,//秒    ));//发送请求$res = file_get_contents($url,false,stream_context_create($opts));


此篇文章由DurkBlue发布,转载请注明来处
文章投稿或转载声明

来源:DurkBlue版权归原作者所有,转载请保留出处。本站文章发布于 2019-12-16
温馨提示:文章内容系作者个人观点,不代表DurkBlue博客对其观点赞同或支持。

赞(0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

阅读
分享

发表评论取消回复

快捷回复:
AddoilApplauseBadlaughBombCoffeeFabulousFacepalmFecesFrownHeyhaInsidiousKeepFightingNoProbPigHeadShockedSinistersmileSlapSocialSweatTolaughWatermelonWittyWowYeahYellowdog

评论列表 (暂无评论,1734人围观)参与讨论

还没有评论,来说两句吧...