php fopen 函数不能获取远程地址内容
fopen函数在php中多半是用于读写文件了,但有时也用于获取远程服务器的文件,但我们在使用fopen读取远程文件时需要开启allow_url_fopen才可以哦。
解决过程, 首先排除了DNS的问题,因为除了这几个函数,其他一切工作正常。虽然是带域名的URL才有问题,但gethostbyname() 这个函数却可以得到正确返回。 然后想到的是php.ini 的配置问题——但发现allow_url_fopen 已经打开。 之后寻求Google帮忙,有人提及是SELINUX的问题。可我压根没有打开SELINUX。继续Google之,发现了StackOverflow的这篇,代码如下:
$file = fopen ( 'http://HdhCmsTestphpfensi测试数据/' , '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://HdhCmsTestphpfensi测试数据/" [ "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可以正常打开远程地址,但遇到本地的地址却会报错,例如代码如下:
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"
查看更多关于php fopen 函数不能获取远程地址内容 - php函数的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did30722