duanqiao1926 2010-12-23 10:21
浏览 24
已采纳

在php中更改图像名称

hi i want to upload image on server and i have done it but the problem is when i upload image with the same name it give me error what i want to do to append something to end of image name so that every image has its own unique name.

$TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name']);
if (file_exists($TARGET_PATH))
{
    // here will be the appended term
}
  • 写回答

3条回答 默认 最新

  • dsvjw20866 2010-12-23 10:25
    关注

    You should do this:

    $TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name']);
    while (file_exists($TARGET_PATH))
    {
        $TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name'],'.jpg') . uniqid() . '.jpg';
    }
    

    That way it will always produce a unique file name. note this will work for files with the extension jpg. should you want to use it for other files then i would recommend this:

      $TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name']);
    $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
    
        while (file_exists($TARGET_PATH))
        {
            $TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name'],'.' .$ext) . uniqid() . '.'.$ext;
        }
    

    supplying an extension to basename will remove the extension from the name. Adding uniqid() will add some unique entropy to the end of the filename. If that's to long for you, you could replace it with rand(0,10);

    This method also has the advantage of only executing when it finds that the file does exist, otherwise it won't run at all.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度