2011-11-29 120 views
0

如何使用PHP將圖像從url上傳到ftp?如何通過FTP使用PHP上傳文件的URL?

想從URL上傳圖像到FTP

如:http://test.com/imagefile.jpghttp://test.com/testvideo.flv

我想該文件通過FTP或捲曲PHP上傳,

我的示例代碼在這裏,但它不」工作。

它說沒有找到文件。

$ftp_server ="ftp.yoursite.com" 
$ftp_user ="yoursite user" 
$ftp_password = "yoursite pass" 
$file_to_upload = "http://test.com/imagefile.png"; 
$remote_location = "/test"; 

// set up connection or exit with message 
$flink = ftp_connect($ftp_server) or exit("Can't connect to ftp server: $ftp_server"); 

// login or at least try 
if(ftp_login($flink, $ftp_user, $ftp_password)) { 


// if login successful use ftp_put to upload the file 
// if you upload binary files use mode FTP_BINARY 
if(ftp_put($flink, $remote_location, $file_to_upload, FTP_ASCII)) { 

    echo "Success! File is uploaded!"; 
} else { 
    echo "Can't upload file"; 

} 
} else { 
echo "Can't login with this user & password"; 

} 

// close the connection 
ftp_close($flink); 

任何人都可以幫助解決這個問題嗎?或者任何人都可以建議比這更好? 謝謝!非常感謝。

+0

$ file_to_upload必須對本地文件的服務器如果你正在使用ftp_put。 – subroutines

回答

0

基本上它像:

 
$connection = ftp_connect($ftp_server); 

$login = ftp_login($connection, $ftp_user, $ftp_password); 

if (!$connection || !$login) { die('Connection attempt failed!'); } 

$upload = ftp_put($connection, $remote_location, $file_to_upload, FTP_ASCII); 

if (!$upload) { echo 'FTP upload failed!'; } 

ftp_close($connection); 


//or you could do as : 

$upload = copy($source, ‘ftp://user:[email protected]/path/file‘); 

這兩種方法都爲我工作。 希望它可以幫助你

+0

嗨,它不工作,我測試代碼$連接= ftp_connect($ ftp_server); $ login = ftp_login($ connection,$ ftp_user,$ ftp_password); if(!$ connection ||!$ login){die('Connection attempt failed!'); $ $ upload = ftp_put($ connection,'uploaded /','http://mysite.com/myfile.jpg',FTP_ASCII); if(!$ upload){echo'FTP upload failed!'; } ftp_close($ connection); – devzone

0

我解決這個案件,首先從給定的URL讀取文件內容,然後將其內容保存到臨時文件,然後使用FTP上傳文件。

代碼:

$config = array(
    'host' => '', 
    'port'  => '', 
    'username' => '', 
    'password' => '' 
); 

function init(array $config) 
{ 
    $port = (!empty($config['port']))? intval($config['port']) : 21; 
    $resource = ftp_connect($config['host'], $port); 
    ftp_login($resource, $config['username'], $config['password']); 
    ftp_pasv($resource, true); 
    return $resource; 
} 

function uploadFile(string $url, $resource) 
{ 
    $data = file_get_contents($url); 
    $tmpFilename = tempnam('/tmp', rand(10, 100) . '_'); 
    file_put_contents($tmpFilename, $data); 
    ftp_put($resource, '/new_file', $tmpFilename, FTP_BINARY); 
    unlink($tmpFilename); 
    ftp_close($resource); 
} 

$resource = init($config); 
uploadFile(
    "https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=1b3cdae197be", 
    $resource 
); 

更多回答有關從網址下載文件,並從另一臺服務器上保存文件,並創建臨時文件 - >firstsecondthird