简体   繁体   English

如何使用php通过ftp抓取文件?

[英]How do I grab files through ftp with php?

I have a setup where should I plug the following direct into my browser: 我有一个安装程序,应将以下内容直接插入浏览器:

ftp://username:p4ssw0rd@ip.ad.dr.ess/Archive/test.txt

Access to the file is granted. 授予对该文件的访问权限。 However I can't seem to grab these files with php, via file_get_contents("$above_url") - I receive the following error: 但是我似乎无法通过php通过file_get_contents("$above_url")来获取这些文件-我收到以下错误:

[function.file-get-contents]: failed to open stream: FTP server reports 550 /Archive/test.txt: not a plain file. [function.file-get-contents]:无法打开流:FTP服务器报告550 /Archive/test.txt:不是纯文件。

Ultimately I want to be able to save files to this location too. 最终,我也希望能够将文件保存到该位置。 Is it obvious what I'm doing wrong here? 很明显我在这里做错了吗?

Instead of using file_get_contents() and hoping that PHP will by default do everything right, I would suggest that you use the FTP extension or the CURL extension instead. 我建议您使用FTP扩展名CURL扩展名,而不是使用file_get_contents()并希望PHP默认情况下可以正确执行所有操作。 They allow you much better control over all settings related to FTP access. 它们使您可以更好地控制与FTP访问相关的所有设置。 Especially considering that you are planning to write to the FTP location as well, you are better off establishing a proper way of dealing with FTP. 特别是考虑到您也计划写入FTP位置,最好建立一种正确的处理FTP的方法。

Try this: 尝试这个:

$c = curl_init("ftp://$username:$password@ftp.example.com/$remote");
// $local is the location to store file on local client
$fh = fopen($local, 'w') or die($php_errormsg); 
curl_setopt($c, CURLOPT_FILE, $fh);
curl_exec($c);
curl_close($c);

You pass the URL to use to curl_init( ). 您将URL传递给curl_init()。 Because the URL begins with ftp://, cURL knows to use the FTP protocol. 由于URL以ftp://开头,因此cURL知道使用FTP协议。 Instead of a separate call to log on to the remote server, you embed the username and password directly into the URL. 您无需将用户名和密码直接嵌入URL中,而无需单独调用即可登录到远程服务器。 Next, you set the location to store the file on your server. 接下来,您设置将文件存储在服务器上的位置。 Now you open a file named $local for writing and pass the file handle to curl_setopt( ) as the value for CURLOPT_FILE. 现在,您打开一个名为$ local的文件进行写入,并将文件句柄传递给curl_setopt()作为CURLOPT_FILE的值。 When cURL transfers the file, it automatically writes to the file handle. 当cURL传输文件时,它将自动写入文件句柄。 Once everything is configured, you call curl_exec( )to initiate the transaction and then curl_close( ) to close the connection. 配置完所有内容后,您可以调用curl_exec()启动事务,然后调用curl_close()关闭连接。

(from java-samples.com) (来自java-samples.com)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM