dthjnc306679 2013-04-18 17:21
浏览 24
已采纳

如果已存在具有该名称的图像,则将数字附加到文件名

I wrote some php that checks if a file already exists when a user uploads a new file, and if so appends a string to the filename. What I want is that a number is added to the end of the filename and when another file with the same name is uploaded it tops the number by 1.

So for example: I already have an image uploaded with filename image.png and I upload another one with the same filename. That file should be renamed to image0.png. When I try to upload another image with filename image.png it should be renamed to image1.png and so on.

I'm not sure how to accomplish this within my code. Can anyone help me out? This is the code snippet that checks for duplicates and appends something to the filename.

if(file_exists("/customers/d/8/e/frankkluytmans.nl/httpd.www/testsite/cms/upload/".$_FILES["image"]["name"]))
{
    $filename = explode(".",$_FILES['image']['name']);
    $imageName = $filename[0]."hoi.".$filename[1];
}
else
{
    $imageName = $_FILES['image']['name'];
}

$image = mysql_real_escape_string(htmlspecialchars("/upload/".$imageName));

if (move_uploaded_file($_FILES["image"]["tmp_name"],     "./upload/".$imageName)) {�

mysql_query("INSERT frankkluytmans SET pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'")
or die(mysql_error()); 

header("Location: index.php"); 

}
  • 写回答

2条回答 默认 最新

  • drwdvftp423507 2013-04-18 17:37
    关注

    You could use a recursive function to keep checking the number:

    function checkFile($path, $file, $ext, $number)
    {
        if(file_exists($path.$file.$number.$ext))
        {
            if($number == "")
                $number = 0;
    
            $number ++;
            return checkFile($path, $file, $ext, $number);
        }
    
        return $path.$file.$number.$ext;
    }
    
    //run mime type things to get extension. for now lets pretend it is .jpg
    // and assume you stripped the extension from the uploaded file...
    // also, pass blank to last param to start the file check without a number.
    
    $extension = ".jpg";
    $filename_minus_extension = "some-image";
    
    $filename = checkFile('path-to-directory/', $filename_minus_extension, $extension, "");
    

    This is in no way tested, but the general idea is to use a recursive function. If you have a specific question, feel free to ask and I may update.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)