|
|
 |
章 37. 使用远程文件
只要在 php.ini 文件中激活了 allow_url_fopen 选项,您可以在大多数需要用文件名作为参数的函数中使用 HTTP 和 FTP URL 来代替文件名。同时,您也可以在 include()、include_once()、require() 及
require_once() 语句中使用 URL。PHP
所支持协议的更多信息参见 附录 L。
注:
要在 PHP 4.0.3 及其以后版本中使用 URL,您需要用 --enable-url-fopen-wrapper 参数来配置 PHP。
例如,您可以用以下范例来打开远程 WEB 服务器上的文件,解析您需要的输出数据,然后将这些数据用在数据库的检索中,或者简单地将其输出到您网站剩下内容的样式匹配中。
例子 37-1. 获取远程文件的标题 |
<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
echo "<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);
?>
|
|
如果您用有合法的访问权限,以一个用户的身份和某 FTP 服务器建立了链接,您还可以向该 FTP 服务器端的文件进行写操作。您仅能用该方法来创建新的文件;如果您尝试覆盖已经存在的文件,fopen() 函数的调用将会失败。
要以“anonymous”以外的用户名连接服务器,您需要指明用户名(甚至密码),例如“ftp://user:password@ftp.example.com/path/to/file”。(如果通过 HTTP 协议访问远程文件时需要基本身份认证,您也可以用使用的语法。)
例子 37-2. 远程服务端的数据存储 |
<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
echo "<p>Unable to open remote file for writing.\n";
exit;
}
/* Write the data here. */
fputs ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>
|
|
注:
您或许可以从以上范例中得到启发,用该技术来存储远程日志文件。但是正如以上提到的,在用 fopen() 方式打开的 URL 中,您仅能对新文件进行写操作。如果远程文件已经存在 fopen() 函数的操作将会失败。要进行类似的分布式日志操作,您可以参考 syslog() 函数。
toby at butzon dot com
19-Apr-2002 08:15
It's important to understand that remote files included/required into your
script are NOT run on your server (as previous posts have suggested).
Think about it this way: When I do this:
<?php
include('http://www.example.com/some-include.php');
?>
..I'm actually asking PHP to make a separate HTTP request
(just as your Web browser would) to www.example.com. So, point your browser
to that location. Do you see any PHP code? No. You will only see HTML/text
content.
(On the off chance that .php wasn't associated with the
PHP module/binary, the code would only be displayed. Thus, you would have
to TRY to make a dangerous include scenario -- such as eval()'ing a remoted
included file specified by the user.)
Therefore, although this code
may be vulnerable to an "untrustworthy information" attack (where
the information displayed by your Web site isn't actually information you
endorse, even though the information is ultimately transferred from your
Web server), you are NOT vulnerable to malicious access to your Web server
resources, even if visitors can specify any remote server/file that they
please.
| |