download a file from ftp using curl and php

My guess is that your URL is pointing towards a directory, not a file. You would need to feed CURLOPT_URL the full URL to the file. Also if you want to download a file you might want to save it somewhere.

Working example:

$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);

  • Set CURLOPT_URL to the full path of the file.
  • Remove the CURLOPT_FTPLISTONLY line.
  • Add these lines before curl_exec:

    $file = fopen("filename_to_save_to", "w");
    curl_setopt($curl, CURLOPT_FILE, $file);
    

Community response works with minor adjustment :

It appears that setting CURLOPT_FILE before setting CURLOPT_RETURNTRANSFER doesn't work, presumably because CURLOPT_FILE depends on CURLOPT_RETURNTRANSFER being set.

Quoting joeterranova's comment on this page: http://php.net/manual/fr/function.curl-setopt.php


See CURL help including how to connect to it via FTP here http://www.linuxformat.co.uk/wiki/index.php/PHP_-_The_Curl_library

NOTE: IF the file can be accessed from HTTP then it is better to just use the link EG: http://host.com/file.txt and then use file_get_contents or file functions.

You can then use http://uk.php.net/file_get_contents or any other way to download the file to your computer. This option will be better than using FTP for download. You can always use FTP to upload as mentioned in the link above.


After trying all of these answers and having none of them work, this is what I finally got to work.

$curl = curl_init();
$fh   = fopen("FILENAME.txt", 'w');
curl_setopt($curl, CURLOPT_URL, "ftp://{$serverInfo['username']}:{$servererInfo['password']}@{$serverInfo['server']}/{$serverInfo['file']}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
fwrite($fh, $result);
fclose($fh);
curl_close($curl);