Tutorial: FTP Upload with PHP and cURL : 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”;
}
echo $message;
?>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s