#native_company# #native_desc#
#native_cta#

FTP Upload With CURL

By C. Rieck
on September 25, 2004

Version: 1

Type: Sample Code (HOWTO)

Category: File Management

License: GNU General Public License

Description: This script demonstrates how to upload files to an FTP server using the PHP support for libcurl.

$server    = 'ftp://ftp.example.com';
$u_name    = 'username';
$p_word    = 'password';
$up_file   = 'file_to_upload.ext';
$srvr_path = '/path_to/upload_directory/';
$new_name  = 'uploade_file.ext';
// Append path & uploaded file name to server name, pass with CURLOPT_URL.
$url = $server . $srvr_path . $new_name; 
// fopen() upload file for handle to pass with CURLOPT_INFILE.
$fp = @fopen($up_file, 'r');
if (!$fp) {
    echo 'Failed to open upload file.' . '<br />';
    exit;
}
if (!($ch = curl_init())) {
    echo 'Unable to allocate resource.' . '<br />';
    exit;
}     
curl_setopt($ch, CURLOPT_URL, $url);  
curl_setopt($ch, CURLOPT_USERPWD, $u_name . ':' . $p_word);
// If true w/CURLOPT_RETURNTRANSFER server output returned by curl_exec().
// (Usually no output w/FTP, anyway.)
// If false, curl_exec() will return true on success.
// Either way curl_exec() returns false on failure.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($ch, CURLOPT_UPLOAD, true);  
curl_setopt($ch, CURLOPT_INFILE, $fp);  
// Pass true w/CURLOPT_TRANSFERTEXT for ascii, false for binary.
curl_setopt($ch, CURLOPT_TRANSFERTEXT, true);  
// File size w/CURLOPT_INFILESIZE must be accurate for clean transfer.
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($up_file));  
// Everything's ready, now curl_exec() does it all.
$curl_return = curl_exec($ch);
if ($curl_return === false) {
    // Show failure info.
    echo 'curl_exec() failed.' . '<br />';
    echo 'curl_errno() = ' . curl_errno($ch) . '<br />';
    echo 'curl_error() = ' . curl_error($ch) . '<br />';
} else {  
    // Show success info.
    echo 'curl_exec() succeeded.' . '<br />';
    echo '<br /><b>curl_getinfo()</b>' . '<br />';
    foreach (curl_getinfo($ch) as $key => $value) {
        echo $tab . $key . ' => ' . $value . '<br />';
    }
}
curl_close($ch);