$_FILES empty, curl with file upload

I’ve been banging my head against the wall on this one. I feel like my problem is something really silly, but I just can’t figure out what.

I have a proxy script, which is handling everything (POST data and uploads).

Read More

When I print_r($_FILES) on the back-end server, it’s an empty array, and $_POST contains the file path.

$ch = curl_init();
$options = array( 
    CURLOPT_HEADER => 1, 
    CURLOPT_HTTPHEADER => array( 
        "Host: {$host}", 
        "Cache-Control: no-cache"
    ), 
    CURLOPT_RETURNTRANSFER => true, 
    CURLOPT_SSL_VERIFYHOST => false, 
    CURLOPT_SSL_VERIFYPEER => 0, 
    CURLOPT_URL => "http://{$this->config->ipAddress}{$url}", 
    CURLOPT_FOLLOWLOCATION => false, 
    CURLOPT_COOKIE => $cookie_string, 
    CURLOPT_USERAGENT => $_SERVER["HTTP_USER_AGENT"]
);

if (! empty($_POST)) {
    if (! empty($_FILES)) {
        //$options[CURLOPT_HTTPHEADER][] = "Content-type: multipart/form-data";

        $files = "";
        foreach ($_FILES as $fid => $file) {
            $files .= "{$fid}=@" . $file["tmp_name"] . ";type={$file["type"]};name={$file["name"]}&";
        }
    }

    $postString = (! empty($files) ? $files : '') . http_build_query($_POST);
    $options[CURLOPT_POST] = 1;
    $options[CURLOPT_POSTFIELDS] = $postString;
}

curl_setopt_array($ch, $options);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

The reason I’m using http_build_query instead of just feeding an array is because we will encounter a multidimensional array.

Thanks!

Related posts

Leave a Reply

1 comment

  1. I’m willing to bet your form enctype isn’t “multipart/form-data” b/c your not passing the post string as an array.

    “If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.”

    You can find out what is going on with the curl by setting the curl option “curl_setopt($ch, CURLOPT_VERBOSE, TRUE); ” and then “print_r( curl_getinfo($ch) );” after the “curl_exec($ch);” and it will output all the information about the request and response.