Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 php file_get_contents函数代理获取远程页面的代码

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

发布时间:2015-08-22   编辑:www.jquerycn.cn
为大家介绍使用php file_get_contents函数的代理方法获取远程网页的方法,当然也可以使用curl模拟代码的方法,如何选择,看大家的实际需要了。

为大家介绍使用php file_get_contents函数的代理方法获取远程网页的方法,当然也可以使用curl模拟代码的方法,如何选择,看大家的实际需要了。

1、php file_get_contents函数获取远程网页
 

复制代码 代码示例:
<?php
$url = "http://www.jquerycn.cn/";
$ctx = stream_context_create(array(
'http' => array('timeout' => 5,
'proxy' => 'tcp://60.175.203.243:8080',
'request_fulluri' => True,)
)
);
$result = file_get_contents($url, False, $ctx);
echo $result;
?>

2、curl 代理的方法:
 

复制代码 代码示例:
<?php
function postPage($url)
{
$response = "";
$rd=rand(1,4);
$proxy='http://212.33.27.253:808';
if($rd==2) $proxy='http://212.88.16.56:8088';
if($rd==3) $proxy='http://202.98.123.126:8080';
if($rd==4) $proxy='http://59.14.97.38:8080';
if($url != "") {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
$response = curl_exec($ch);
if(curl_errno($ch)) $response = "";
curl_close($ch);
}
return $response;
}

附:
使用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
例子:
 

复制代码 代码示例:
<?php
$serverAddress = 'http://s.jquerycn.cn';
//获得外域文件内容
$randomNumber = file_get_contents($serverAddress);
//输出内容
echo $randomNumber;
?>

您可能感兴趣的文章:
php file_get_contents函数抓取页面信息的代码
php读取远程文件的三种方法分享
PHP读写文件生成HTML的代码举例
php 获取远程网页内容简单函数
php file_get_contents函数代理获取远程页面的代码
PHP fopen/file_get_contents与curl性能比较
PHP 获取远程网页内容的代码
PHP 抓取内容中图片并下载保存的代码
php打开远程文件的方法与风险防范
php中curl、fsocket、file_get_content函数比较

[关闭]