簡體   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