FTP 和 FTPS

PHP 3,PHP 4,PHP 5。自 PHP 4.3.0 起支持 ftps://

  • ftp://example.com/pub/file.txt

  • ftp://user:password@example.com/pub/file.txt

  • ftps://example.com/pub/file.txt

  • ftps://user:password@example.com/pub/file.txt

允许对已有文件进行只读访问以及通过 FTP 建立新文件。如果服务器不支持被动模式的 ftp,则连接会失败。

可以用读或者写的方式打开文件,但不能同时是读写。如果 ftp 服务器上已经存在远程文件而试图用写的方式打开但又没有指定 overwrite 的上下文选项,则连接会失败。如果想通过 ftp 更新已有的文件,则在上下文中指定 overwrite 选项并用写的方式打开。还可以用 FTP 扩展

追加文件: 自 PHP 5.0.0 起可以通过 ftp:// URL 协议来追加文件。在之前的版本试图通过 ftp:// 来追加文件会导致失败。

ftps:// 是 PHP 4.3.0 引进的。它和 ftp:// 相同,但是尝试和 ftp 服务器建立一个安全连接。如果服务器不支持 SSL,则会返回一个普通的未加密的 ftp 连接。

注: 自 PHP 4.3.0 起开始支持 FTPS,需要在编译时加入 OpenSSL 的支持。

表格 L-4. Wrapper Summary

属性PHP 4PHP 5
受限于 allow_url_fopen
允许读取
允许写入是(仅允许写入新文件)是(允许使用 overwrite 参数覆盖新文件)
允许附加是(PHP 5.0.0 或更新版本)
允许同时读写
支持 stat() PHP 5.0.0:仅在 filesize()filetype()file_exists()is_file()is_dir() 中支持。PHP 5.1.0:filemtime()
支持 unlink()
支持 rename()
支持 mkdir()
支持 rmdir()

表格 L-5. 上下文选项(自 PHP 5.0 起)

名称用法默认值
overwrite允许覆盖远程服务器上已存在的文件。仅适用于写入模式(上传)。FALSE(禁用)
resume_pos开始传输的文件偏移量。仅适用于读取模式(下载)。0(文件头)
proxy(PHP 5.1.0 或更高版本) 通过 HTTP 代理服务器对 FTP 发出请求 仅能进行文件读取操作。 例如:tcp://squid.example.com:8000  

底层套接字流上下文选项(Underlying socket stream context options): 有可能通过底层传输(underlying transport)支持附加的上下文选项。对于 ftp:// 流,参考 tcp:// 传输的上下文选项。对于 ftps:// 流,参考 ssl:// 传输的上下文选项。


add a note add a note User Contributed Notes
wlangdon at essex dot ac dot uk
10-Oct-2006 12:32
old fashioned FTP servers may not be compatible with ftp_connect().
26-Sep-2005 11:33
<?
$str
="replace all contenents";
$filew="ftp://gufo:gufo@192.168.1.55:21/jj.php";
$opts = array('ftp' => array('overwrite' => true));
$context = stream_context_create($opts);
$strwri = file_put_contents($filew,$str,LOCK_EX,$context);
?>
php at f00n dot com
04-Jul-2004 03:39
For Intranet purposes I found I preferred to move my file via ftp functions to match the session user's ftp account and put the file in a holding bay so I knew who it was from.

The FTP wrapper method will NOT do this if your ftp server does NOT support passive mode.

eg.  an ftp server behind NAT/routing