首页  >  文章  >  后端开发  >  php怎么设置useragent

php怎么设置useragent

藏色散人
藏色散人原创
2021-05-20 09:13:522687浏览

php设置useragent的方法:1、用curl设置user_agent,代码如“curl_setopt($curl, CURLOPT_USERAGENT...)”;2、用file_get_contents设置user_agent。

php怎么设置useragent

本文操作环境:Windows7系统、PHP7.1版,DELL G3电脑

最近有在用PhpQuery,发现抓取一些网页的内容是空内容,询问了解到是设置了判断User Agent这个属性。于是一直在找PhpQuery怎么设置UserAgent,无奈PhpQuery文档太少,暂时没有找到,便去寻找PHP原生设置UserAgent的方法,找到了两种。

无User Agent代码:

html(),"mochoublog",false))  
{  
    echo "存在";  
}  
else{  
    echo "不存在";  
}  
?>

 效果:

页面输出“不存在”

有User Agent代码:

html(),"mochoublog",false))  
{  
    echo "存在";  
}  
else{  
    echo "不存在";  
}  
?>

效果:

页面输出“存在”

 用curl设置user_agent:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://www.baidu.com/');
curl_setopt($curl, CURLOPT_USERAGENT, 'Chrome 42.0.2311.135');//这里设置UserAgent为[Chrome 42.0.2311.135]
$data = curl_exec($curl);//这里得到的是抓取的内容
curl_close($curl);

 用file_get_contents设置user_agent:

ini_set('user_agent', 'Chrome 42.0.2311.135');

如果是用PhpQuery去抓取网页的话用第二种方法去设置UserAgent,方法一是无效的。但是如果你直接用curl去抓取网页的话当然是用方法一的“curl_setopt($curl, CURLOPT_USERAGENT,'Input user agent')”直接设置就好了。

 推荐学习:《PHP视频教程

以上是php怎么设置useragent的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn