在PHP中使用远程文件

一、 介绍

只要在 php.ini 文件中激活了 allow_url_fopen 选项,您可以在大多数需要用文件名作为参数的函数中使用 HTTP 和 FTP URL 来代替文件名。同时,您也可以在 include()、include_once()、require() 及 require_once() 语句中使用 URL。PHP 所支持协议的更多信息参见 附录 J。

注: 要在 PHP 4.0.3 及其以后版本中使用 URL,您需要用 --enable-url-fopen-wrapper 参数来配置 PHP。 Windows 版本的 PHP 4.3 版之前不支持以下函数的远程访问:include(),include_once(),require(),require_once() 以及 参考 XLI, 图像函数库 扩展库中的 imagecreatefromXXX 函数。

例如,您可以用以下范例来打开远程 WEB 服务器上的文件,解析您需要的输出数据,然后将这些数据用在数据库的检索中,或者简单地将其输出到您网站剩下内容的样式匹配中。

例子 x. fopen() 例子

1   
2$handle = fopen ("/home/rasmus/file.txt", "r");   
3$handle = fopen ("/home/rasmus/file.gif", "wb");   
4$handle = fopen ("http://www.andsky.com/", "r");   
5$handle = fopen ("ftp://user:[email protected]/somefile.txt", "w");   

例子 X. 获取远程文件的标题

1   
2$file = fopen ("http://www.andsky.com/", "r");   
3if (!$file) {   
4echo "

<p>Unable to open remote file.\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
/* This only works if the title and its tags are on one line /
if (eregi ("<title>(.
)</title>", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);

 1
 2  
 3如果您用有合法的访问权限,以一个用户的身份和某 FTP 服务器建立了链接,您还可以向该 FTP 服务器端的文件进行写操作。您仅能用该方法来创建新的文件;如果您尝试覆盖已经存在的文件,fopen() 函数的调用将会失败。 
 4
 5要以“anonymous”以外的用户名连接服务器,您需要指明用户名(甚至密码),例如“ftp://user:[email protected]/path/to/file”。(如果通过 HTTP 协议访问远程文件时需要基本身份认证,您也可以用使用的语法。) 
 6
 7例子 X. 远程服务端的数据存储 
 8
 9<?php   
10$file = fopen ("ftp://ftp.andsky.com/incoming/outputfile", "w");   
11if (!$file) {   
12echo "<p>Unable to open remote file for writing.\n";   
13exit;   
14}   
15/* Write the data here. */   
16fputs ($file</p>
Published At
Categories with 网络技术
comments powered by Disqus