PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

php file_get_contents函数代理获取远程页面的代码

原创
2016-07-25 09:04:19 870浏览
  1. $url = "http://bbs.it-home.org/";
  2. $ctx = stream_context_create(array(
  3. 'http' => array('timeout' => 5,
  4. 'proxy' => 'tcp://60.175.203.243:8080',
  5. 'request_fulluri' => True,)
  6. )
  7. );
  8. $result = file_get_contents($url, False, $ctx);
  9. echo $result;
  10. ?>
复制代码

2、curl 代理的方法:

  1. function postPage($url)
  2. {
  3. $response = "";
  4. $rd=rand(1,4);
  5. $proxy='http://212.33.27.253:808';
  6. if($rd==2) $proxy='http://212.88.16.56:8088';
  7. if($rd==3) $proxy='http://202.98.123.126:8080';
  8. if($rd==4) $proxy='http://59.14.97.38:8080';
  9. if($url != "") {
  10. $ch = curl_init($url);
  11. curl_setopt($ch, CURLOPT_HEADER, 0);
  12. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  13. curl_setopt($ch, CURLOPT_PROXY, $proxy);
  14. $response = curl_exec($ch);
  15. if(curl_errno($ch)) $response = "";
  16. curl_close($ch);
  17. }
  18. return $response;
  19. }
复制代码

附: 使用php file_get_contents解决ajax垮域的问题

在ajax运用中,有时会垮域调用文件,而浏览器为了安全会默认给这种操作提出警告,甚至直接阻止。如果是IE会弹出一个警告窗口,询问你是否继续操作,只有你同意了IE才会调用垮域的文件。而其它浏览器,如火狐、Opera默认设置下则会直接提示错误,阻止调用外域文件。这会给用户不好的操作体验,如果想通过用户修改浏览器的安全设置来解决这个问题是不现实的,最好是在服务器端解决。

在服务器端可以使用一个同域的文件做为代理文件,这个代理文件将获得外域文件的内容,然后再传递给ajax。这样ajax就不是调用外域文件,而是调用同域的这个代理文件,安全问题也就解决了。

如果服务器端支持PHP,可以使用file_get_contents函数,详细用法可参考:http://www.w3school.com.cn/php/func_filesystem_file_get_contents.asp 例子:

  1. $serverAddress = 'http://s.jbxue.com';
  2. //获得外域文件内容
  3. $randomNumber = file_get_contents($serverAddress);
  4. //输出内容
  5. echo $randomNumber;
  6. ?>
复制代码


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