如何使用PHP通过ftp从url上传文件?

时间:2011-11-29 05:10:42

标签: php file-upload curl upload ftp

如何使用php将图像从url上传到ftp?

想要将图片从网址上传到ftp

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

我希望通过FTP或curl 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);

任何人都可以帮助解决这个问题吗?或者任何人都可以建议比这更好? 谢谢!非常感谢。

2 个答案:

答案 0 :(得分: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:password@host/path/file‘);

这两种方法对我有用。 希望它能帮到你

答案 1 :(得分: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
);

有关从url下载文件的更多答案,并从另一台服务器保存文件并创建临时文件 - > firstsecondthird