dsqtl335227
2014-11-06 22:50
浏览 339
已采纳

上传的文件总是被覆盖

I have this php code that uploads a photo from the iPhone into this directory. The problem I have is that each time a photo is uploaded it overwrites the previous one. How can I get it so all the images are stored?

<?php
$name = "image";
$path = "uploaded/".$name.".jpg";
$output = "{\"response\":\"false\"}";   
if(move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
     $output = "{\"response\":\"true\"}";
}
echo $output;
?>

图片转代码服务由CSDN问答提供 功能建议

我有这个PHP代码,可将iPhone上的照片上传到此目录中。 我遇到的问题是,每次上传照片时都会覆盖上一张照片。 如何获取所有图像?

 &lt;?php 
 $ name =“image”; 
 $ path =“uploaded /".$  name。“。jpg”; 
 $ output =“{\”response \“:\”false \“}”;  
if(move_uploaded_file($ _ FILES ['image'] ['tmp_name'],$ path)){
 $ output =“{\”response \“:\”true \“}”; 
} 
echo $ 输出; 
?&gt; 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dougu5847 2014-11-06 22:51
    已采纳

    Each time you upload a file, you move it to the same directory with the same name.

    There are many things that you can do the simplest being.

    // produces something like image-1415317895-545c0987ce42c5
    $name = "image-" . uniqid(time() . "-");
    

    You should also look into verifying that the uploaded file is indeed an image.

    $info = getimagesize($_FILES['image']['tmp_name']); 
    
    if (is_array($info) && array_key_exists('mime', $info) && $info['mime'] === 'image/jpeg') {
        move_uploaded_file($_FILES['image']['tmp_name'], $path);
    }
    

    Resources:

    uniqid()
    time()
    getimagesize()

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongsi1944 2014-11-06 22:55

    They're overridden because they have the same name.

    In order to tackle this we would have to make every name unique, I think the best way to do this is like this:

    $name = "image_" . sha1 (openssl_random_pseudo_bytes (100));
    

    This way you are absolutely sure the name will be unique.

    Should it be the case that OpenSSL is not installed then mt_random () is a great alternative.

    $name = "image_" . sha1 (mt_random (0, 1000000));
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题