lodkkx
lodkkx

Reputation: 1173

CURL uploads blank file by FTP

I am using this curl script to try to upload user selected files by FTP. It uploads the files to the server but they are all blank. Why is this happening?

if (!empty($_FILES['userfile']['name'])) {
    $ch = curl_init();
    $localfile = $_FILES['upload']['tmp_name'];
    $fp = fopen($localfile, 'r');
    curl_setopt($ch, CURLOPT_URL, 'ftp-addy-here'.$_FILES['userfile']['name']);
    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) {
            $error = 'File uploaded succesfully.';
        } else {
            $error = 'File upload error.';
        }
 } else {
        $error = 'Please select a file.';
 }

echo $error;

Upvotes: 1

Views: 1119

Answers (2)

eric
eric

Reputation: 56

Line 3, right now it says:

$localfile = $_FILES['upload']['tmp_name'];

Change it to:

$localfile = $_FILES['userfile']['tmp_name'];

Upvotes: 4

Marc B
Marc B

Reputation: 360762

You didn't check if the initial file upload succeeded. Checking for the presence of the remote filename is NOT an indication that it got uploaded. The 100% reliable method to ensure the upload worked is

if ($_FILES['userfile']['error'] === UPLOAD_ERR_OK) {
  ... ftp stuff ...
} else {
    die("Upload failed with error code: {$_FILES['userfile']['error']}");
}

The codes/constants are documented here: http://php.net/manual/en/features.file-upload.errors.php

Upvotes: 1

Related Questions