Uploading To FTP Using PHP and CURL

An interesting project that I was working on today required grabbing remote files to a server and then pushing them to a remote FTP server.

PHP has built in FTP functions, but there are many reasons that you might want to use CURL instead.

Here is the code that I used to upload to FTP, slightly modified for portability:

<?php
$ch = curl_init();
$localfile = “test.tar”;
$fp = fopen($localfile, ‘r’);

curl_setopt($ch, CURLOPT_URL, ‘ftp://username:password@ftp.domain.com/public_html/filesfromscript/’.$localfile);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));

curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);

if ($error_no == 0) {
$message = ‘File uploaded successfully.’;
} else {
$message = “File upload error: $error_no. Error codes explained here http://curl.haxx.se/libcurl/c/libcurl-errors.html”;
}
echo $message;
?>

Tags: , , ,


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply