繁体   English   中英

使用PHP中的curl从FTP下载文件

[英]Download file from FTP using curl in php

我正在制作一个旨在在CLI中运行的php脚本,这将帮助我在ftp服务器上下载文件。 我将向您确切说明问题所在,但在向您解释上下文之前,我将向您展示。

我在共享旧游戏图像文件的网站上注册。 当我们想在该站点上下载文件时,必须登录以获取下载链接。 然后,给出的链接是FTP下载链接。

我使用Wireshark捕获了FTP连接数据包,也将其与失败的脚本化FTP传输进行了比较。

因此,.. FTP服务器接受匿名连接。 当我使用浏览器下载文件时,该文件的链接就是这样。

ftp://website.url/somefolder/1/foo/bar/SOMEOLDIE.rar

现在,如果我使用FileZilla连接到该FTP,并通过匿名登录获得访问权限,我会看到一些文件夹,但是当我进入必须放置iso的“ somefolder”时,该文件夹为空。

看这张图片,然后我将向您展示代码。 在此处输入图片说明 现在的代码;

function download_file($url){
    echo "Downloading: ".$url;
    $ch = curl_init($url);
    $fp = fopen("data/output.rar", "w");
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'data/cookies.txt');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    //curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    //curl_setopt($ch, CURLOPT_FTPLISTONLY, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, "anonymous:mozilla@example.com");
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    //var_dump(curl_getinfo($ch));
    //echo curl_error($ch);
    curl_close($ch);
    fclose($fp);
}

有人可以帮我吗? 我不熟悉curl,我不知道如何告诉curl准确发送我想要的命令。

谢谢 !

编辑:看看这个,它完全一样的问题; 需要帮助,使用PHP和Curl从FTP下载文件

好的,我明白了:)

我将ftp_ *函数用于ftp,而不是curl,因为curl试图更改目录,但是在此ftp服务器上不允许这样做,所以我使用的代码是:

$local_file = 'output.rar';
$server_file = '/somedir/1/bar/foo/somearchive.rar';
$ftp_user_name='anonymous';
$ftp_user_pass='mozilla@example.com';
$ftp_server='server.host';
// set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

/* uncomment if you need to change directories
if (ftp_chdir($conn_id, "<directory>")) {
    echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";
} else { 
    echo "Couldn't change directory\n";
}
*/

// try to download $server_file and save to $local_file
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

// close the connection
ftp_close($conn_id);

有用 !!

您需要向CURLOPT_URL提供文件的完整URL。 另外,如果您要下载文件,则可能要将其保存在某处。

工作示例:

$curl = curl_init();
$file = fopen("ls-lR.gz", 'w');
curl_setopt($curl, CURLOPT_URL, "ftp://ftp.sunet.se/ls-lR.gz"); #input
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FILE, $file); #output
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]");
curl_exec($curl);
curl_close($curl);
fclose($file);

暂无
暂无

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

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