解决过程
首先排除了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中
代码如下 复制代码
运行结果
string(1) 1 string(1) 2
http://www.bkjia.com/phpjc/632063.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/632063.htmltecharticlefopen函数在php中多半是用于读写文件了,但有时也用于获取远程服务器的文件,但我们在使用fopen读取远程文件时需要开启allow_url_fopen才可以...