Tuesday, November 24, 2009

PHP Curl download via FTP access - Part 1

Downloading files via FTP in PhP is fairly easy even if you need FTP access. If your host supports it you just grab the file via PhP's fgets() function (or fread() if u need binary-safe). If you do need FTP access heres a quick snippet to connect:

$fp = ftp_connect($ftpServer);
$lh = ftp_login($fp, $ftpUser, $ftpPass);
$data = fgets($fp);
And you have your file;

additionally you can add a file_put_contents($local, $data); to write it to your local server.
However if your host doesn't support this you'll have to go with the curl method. First step is to make sure the library is installed on your server. Most come with it pre-installed these days so you should be good but to check simple echo phpinfo() and search for "curl" to see what you have.
Next step is to login to FTP via curl which you can do using this format:
$url = "ftp://$ftpUser:$ftpPass@$ftpServer";
it is a good idea to urlencode() your $ftpUser and $ftpPass because if it has a semicolon or at symbol most servers won't know how to interpret what you are trying to do. (Took me like an hour to figure out why it wasn't working for me :\). Once you know you have access you can continue the script and download a remote file to your local server as follows:

$ftpServer = <hosted_file>;
$ftpUser = urlencode(<ftp_user_name>);
$ftpPass = urlencode(<ftp_password>);
$local = <local_file_location>; //be sure to use full path here
$url = "ftp://$ftpUser:$ftpPass@$ftpServer";
$cp = curl_init();
$fp = fopen($local, "w");
curl_setopt($cp, CURLOPT_URL,$url);
curl_setopt($cp, CURLOPT_FILE, $fp);
curl_setopt($cp, CURLOPT_HEADER, 0);

curl_exec($cp);
curl_close($cp);
fclose($fp);

Hope this saves someone hours of time researching.

No comments: