Multiple file uploads with cURL

Josh picture Josh · Aug 9, 2011 · Viewed 8.1k times · Source

I'm using cURL to transfer image files from one server to another using PHP. This is my cURL code:

// Transfer the original image and thumbnail to our storage server
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://' . $server_data['hostname'] . '.localhost/transfer.php');
curl_setopt($ch, CURLOPT_POST, true);
$post = array(
    'upload[]' => '@' . $tmp_uploads . $filename,
    'upload[]' => '@' . $tmp_uploads . $thumbname,
    'salt' => 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); 
$resp = curl_exec($ch);

This is the code in transfer.php on the server I'm uploading to:

if($_FILES && $_POST['salt'] == 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q')
{
    // Save the files
    foreach($_FILES['upload']['error'] as $key => $error)
    {
        if ($error == UPLOAD_ERR_OK)
        {
            move_uploaded_file($_FILES['upload']['tmp_name'][$key], $_FILES['upload']['name'][$key]);
        }
    }
}

All seems to work, apart from one small logic error. Only one file is getting saved on the server I'm transferring to. This is probably because I'm calling both images upload[] in my post fields array, but I don't know how else to do it. I'm trying to mimic doing this:

<input type="file" name="upload[]" />
<input type="file" name="upload[]" />

Anyone know how I can get this to work? Thanks!

Answer

David Chan picture David Chan · Aug 10, 2011

here is your error in the curl call...

var_dump($post)

you are clobbering the array entries of your $post array since the key strings are identical...

make this change

$post = array(
    'upload[0]' => '@' . $tmp_uploads . $filename,
    'upload[1]' => '@' . $tmp_uploads . $thumbname,
    'salt' => 'q8;EmT(Vx*Aa`fkHX:up^WD^^b#<Lm:Q'
);