douke9379 2015-01-20 10:12
浏览 111
已采纳

如果存在,PHP重命名文件名

I have code working which uploads a file whilst checking that the extension is allowed and it is within size limits, but I need to rename the uploaded file if it already exists. I've read a couple of the other posts on this, but I can't work out exactly where I need to fit the suggested code into my current code. Many thanks for any help!

<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="image"/>
    <input type="submit" value="Upload" />
</form>

<?php
    if (isset ($_FILES['image'])) {

        $errors = array();
        $allowed_ext = array('pdf','jpg');

        $file_name = $_FILES['image']['name'];
        $file_ext = strtolower(end(explode('.', $file_name)));
        $file_size = $_FILES['image']['size'];
        $file_tmp = $_FILES['image']['tmp_name'];

        if (in_array($file_ext, $allowed_ext) === false ) {
            $errors[] = '<li>Extension not allowed.</li>';
        }

        if ($file_size > 2097152) {
            $errors[] = '<li>File size must be 2mb or less.</li>';
        }
        if ()

        if (empty($errors)) {
            if (move_uploaded_file($file_tmp, 'images/'.$file_name)) {
                    echo '<li>File uploaded sucessfully.</li>';
                    echo '<li>File located at: http://' . $_SERVER[HTTP_HOST] . '/image-upload/images/' . $file_name . '</li>';
            }

        } else {
            foreach ($errors as $error) {
                echo $error, '<br />';
            }
        }
    }
?>
  • 写回答

2条回答 默认 最新

  • dongwen9975 2015-01-20 10:22
    关注

    Just put this code in place of your blank if()

    if (file_exists('images/'.$file_name))
    {
        $file_name = time().$_FILES['image']['name']; //This will rename file with current time stamp which will always unique.
    }
    

    But i strongly recommend you to always rename your file to save it from any direct access or harm.

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

报告相同问题?

悬赏问题

  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥15 在现有系统基础上增加功能