简体   繁体   中英

Multiple file uploads with cURL

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!

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'
);

The code itself looks ok, but I don't know about your move() target directory. You're using the raw filename as provided by the client (which is your curl script). You're using the original uploaded filename (as specified in your curl script) as the target of the move, with no overwrite checking and no path data. If the two uploaded files have the same filename, you'll overwrite the first processed image with whichever one got processed second by PHP.

Try putting some debugging around the move() command:

if (!move_uploaded_file($_FILES['upload']['tmp_name'][$key], $_FILES['upload']['name'][$key])) {
   echo "Unable to move $key/";
   echo $_FILES['upload']['tmp_name'][$key];
   echo ' to ';
   echo $_FILES['upload']['name'][$key];
}

(I split the echo onto multiple lines for legibility).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM