PHP使用cURL替代file_get_contents函数

curl和file_get_contents都可以在PHP下面获取网页的内容

然而curl会缓存DNS记录,因此性能比file_get_contents函数性能更好

推荐使用curl获取网页内容

下面是利用curl重写的函数,具备file_get_contents相同的功能

function curl_file_get_contents($url)   
{   
    $ch = curl_init();   
    curl_setopt($ch, CURLOPT_URL, $url);            //设置访问的url地址   
    //curl_setopt($ch,CURLOPT_HEADER,1);            //是否显示头部信息   
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);           //设置超时   
    curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);   //用户访问代理 User-Agent   
    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);        //设置 referer   
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);      //跟踪301   
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);    //https请求不验证证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);    //https请求不验证hosts   
    $r = curl_exec($ch);   
    curl_close($ch);   
    return $r;   
}  


附带记录个人需要的API
$image_url  =  "your image url" ;  
$api_key  =   " your api  key"  ;
$newimgurl = "https://www.moderatecontent.com/api/v2?key=" . $api_key . "&url=". $image_url   ;
$apicontent = json_decode(  curl_file_get_contents($newimgurl)   )  ;
$apiletter = $apicontent->rating_letter ;


20221107附带crul doh:
PHP8.1支持 CURLOPT_DOH_URL 选项
  if (defined('CURLOPT_DOH_URL')) {
        curl_setopt($curl, CURLOPT_DOH_URL, 'https://cloudflare-dns.com/dns-query');
        }

自用需要JSON转IP
先通过curl获取IP
https://dns.google/resolve?name=example.com&type=a

获取数据后,jsondecode 输出IP
$ip=$re->Answer[0]->data

最后二次curl获取其他URL数据时指定IP
curl_setopt($ch, CURLOPT_RESOLVE, array($domain.':443:'.$ip));

curl_setopt($ch, CURLOPT_RESOLVE, array('example.com:443:93.184.216.34'));

由于网上都是相互转载的,本人无法确认出处,就不写来源了
Client URL Library :
http://www.php.net/manual/en/book.curl.php
file_get_contents:
http://php.net/manual/en/function.file-get-contents.php

此处评论已关闭