Reputation: 305
How to upload image from url to ftp using php?
want to upload image from url to ftp
eg: http://test.com/imagefile.jpg or http://test.com/testvideo.flv
I want that file to upload via FTP or curl php,
I have sample code here but it doesn't work.
It say's no file found.
$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);
Any one can help this problem? Or anyone can suggest better than this ? Thank you! help very much appreciated.
Upvotes: 0
Views: 5965
Reputation: 5169
I solved this case by first read file content from given URL then save it's content into temporary file then use ftp to upload file.
code:
$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
);
More answer about download file from url and save file from another server and create temporary file -> first, second, third
Upvotes: 2
Reputation: 100175
Basically its like:
$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‘);
Both the methods worked for me. Hope it helps you
Upvotes: 0