Jeff Walden Jeff Walden - 1 month ago 12
PHP Question

Warning: ftp_put() expects parameter 3 to be a valid path, string given

I'm attempting to get a file from a URL and then upload that file via FTP to another server with PHP. I'm receiving the error Warning: ftp_put() expects parameter 3 to be a valid path, string given

// file to move:
$local_file = file_get_contents("http://cdn.server.com/affiliate/1.jpg");
$ftp_path = "/virtualhosts/path/for/upload/1.jpg";

// connect to FTP server (port 21)
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");

// send access parameters
$ftp_login = ftp_login($conn_id, $usr, $pwd) or die("Cannot login");

// turn on passive mode transfers (some servers need this)
//ftp_pasv($conn_id, true);

// perform file upload
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_BINARY);

var_dump($upload);
exit();


The var_dump() of $upload is NULL. The URL is correct (obviously not in this example) as I can var_dump the $local_file and see the contents.

How do I convert the string returned in file_get_contents() to a resource that can be used with the ftp_put() function?

Answer

As @nospor and the php manual say, you need to provide a valid path not the contents of the file. It seems that http://cdn.server.com/affiliate/1.jpg isn't located on your server, based on that, you can use copy() to download the remote file and then upload it to the remote server, something like:

<?php

$remoteFile = "http://cdn.server.com/affiliate/1.jpg";
// get the filename of the remote file(1.jpg)
$localFile = basename($remoteFile).PHP_EOL;
// copy the remote file to /tmp/1.jpg
copy($remoteFile, "/tmp/".$localFile);
$ftp_path = "/virtualhosts/path/for/upload/$localFile";
// connect to FTP server (port 21)
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
// send access parameters
$ftp_login = ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
// perform file upload
$upload = ftp_put($conn_id, $ftp_path, "/tmp/".$localFile, FTP_BINARY);
// delete the temporary file
unlink("/tmp/".$localFile);
exit();
Comments