一聚教程网:一个值得你收藏的教程网站

热门教程

php fopen 函数不能获取远程地址内容

时间:2022-06-24 23:32:43 编辑:袖梨 来源:一聚教程网

解决过程

首先排除了DNS的问题,因为除了这几个函数,其他一切工作正常。虽然是带域名的URL才有问题,但gethostbyname() 这个函数却可以得到正确返回。 然后想到的是php.ini 的配置问题——但发现allow_url_fopen 已经打开。 之后寻求Google帮忙,有人提及是SELINUX的问题。可我压根没有打开SELINUX。继续Google之,发现了StackOverflow的这篇

 代码如下 复制代码

$file = fopen('http://www.google.com/', 'rb');
var_dump(stream_get_meta_data($file));

/*
输出结果:
array(10) {
  ["wrapper_data"]=>
  array(2) {
    ["headers"]=>
    array(0) {
    }
    ["readbuf"]=>
    resource(38) of type (stream)
  }

  ["wrapper_type"]=>
  string(4) "cURL"

  ["stream_type"]=>
  string(4) "cURL"

  ["mode"]=>
  string(2) "rb"

  ["unread_bytes"]=>
  int(0)

  ["seekable"]=>
  bool(false)

  ["uri"]=>
  string(23) "http://www.google.com/"

  ["timed_out"]=>
  bool(false)

  ["blocked"]=>
  bool(true)

  ["eof"]=>
  bool(false)

}*/

要使用fopen、getimagesize或include等函数打开一个url,需要对php.ini进行设置,通常设置allow_url_fopen为on允许fopen url,设置allow_url_include为on则允许include/require url,但在本地测试环境下却不一定管用


allow_url_fopen = on

Whether to allow the treatment of URLs (like http:// or ftp://) as files.

allow_url_include = on

Whether to allow include/require to open URLs (like http:// or ftp://) as files.

在本地wamp测试环境中,这样设置以后,fopen可以正常打开远程地址,但遇到本地的地址却会报错,例如

 代码如下 复制代码
1 fopen("http://localhost/myfile.php", "r");

就会在超过php.ini中设置的脚本最长执行时间后报错,告知文件不存在等。这在在线服务器上是不会出现的,但如果将localhost替换成127.0.0.1,却可以正常工作。

从状况看,问题出在DNS解析上,按理说localhost已经自动被映射到127.0.0.1,实际上访问http://localhost和访问http://127.0.0.1也到达同一个地址。

解决的方法就是检查一下Windows的host文件,通常位于system32目录下,一个系统盘是C盘的host路径如下所示

 代码如下 复制代码

C:/Windows/System32/drivers/etc/hosts

打开hosts文件,用记事本或者notepad++等工具

将下面的127.0.0.1前面的#去掉即可。

 代码如下 复制代码

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost

将url视为文件有什么用
比如给include的文件传值,可以这样

 代码如下 复制代码

在example.inc.php中

 代码如下 复制代码

var_dump($_GET['foo']);   
var_dump($_GET['bar']);
?>

运行结果

string(1) "1" string(1) "2"

热门栏目