当前位置:Gxlcms > PHP教程 > PHP下通过file_get_contents的代理使用方法_php技巧

PHP下通过file_get_contents的代理使用方法_php技巧

时间:2021-07-01 10:21:17 帮助过:40人阅读

PHP使用file_get_contents的代理方法获取远程网页的代码。
代码如下:
  1. <br><!--?php <BR-->$url = "http://www.gxlcms.com/"; <br>$ctx = stream_context_create(array( <br>'http' => array('timeout' => 5, <br>'proxy' => 'tcp://60.175.203.243:8080', <br>'request_fulluri' => True,) <br>) <br>); <br>$result = file_get_contents($url, False, $ctx); <br>echo $result; <br>?> <br> <br>另外一种 curl 的方式使用代理的方法: <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>function postPage($url) <br>{ <br>$response = ""; <br>$rd=rand(1,4); <br>$proxy='http://221.214.27.253:808'; <br>if($rd==2) $proxy='http://222.77.14.56:8088'; <br>if($rd==3) $proxy='http://202.98.123.126:8080'; <br>if($rd==4) $proxy='http://60.14.97.38:8080'; <br>if($url != "") { <br>$ch = curl_init($url); <br>curl_setopt($ch, CURLOPT_HEADER, 0); <br>curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); <br>curl_setopt($ch, CURLOPT_PROXY, $proxy); <br>$response = curl_exec($ch); <br>if(curl_errno($ch)) $response = ""; <br>curl_close($ch); <br>} <br>return $response; <br>} <br><br><strong>用file_get_contents解决ajax垮域问题 <br></strong><br>在ajax运用中有时候会垮域调用文件,而浏览器为了安全会默认给这种操作提出警告,甚至直接阻止。如果是IE会弹出一个警告窗口,询问你是否继续操作,只有你同意了IE才会调用垮域的文件。而其它浏览器,如火狐、Opera默认设置下则会直接提示错误,阻止调用外域文件。这会给用户不好的操作体验,如果想通过用户修改浏览器的安全设置来解决这个问题是不现实的,最好是在服务器端解决。 <br><br>在服务器端可以使用一个同域的文件做为代理文件,这个代理文件将获得外域文件的内容,然后再传递给ajax。这样ajax就不是调用外域文件,而是调用同域的这个代理文件,安全问题也就解决了。 <br><br>如果你的服务器端支持PHP的话,可以使用file_get_contents这个函数,看到它的名称就已经知道它有获得其它文件内容的功能了。它的详细用法可以参看PHP官方网站上的file_get_contents用法一页,下面是它的简单实例。 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br><!--?php <BR-->$serverAddress = 'http://s.jb51.net'; <br>//获得外域文件内容 <br>$randomNumber = file_get_contents($serverAddress); <br>//</li></ol></pre>输出内容 <br>echo $randomNumber; <br>?> <br> </li></ol></pre>

人气教程排行