Multiple file uploads with cURL

岁酱吖の 提交于 2019-12-04 03:24:28

问题


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!


回答1:


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



回答2:


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).



来源:https://stackoverflow.com/questions/7003337/multiple-file-uploads-with-curl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!