简体   繁体   English

PHP重命名文件名(如果存在)

[英]PHP Rename File name if Exists

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 />';
            }
        }
    }
?>

Seems your second parameter of move_uploaded_file is incorrect. 似乎您的move_uploaded_file的第二个参数不正确。

$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/image-upload/images/' . $file_name;
move_uploaded_file($file_tmp, $targetPath);

You can echo your $targetPath to check if it's right. 您可以回显$targetPath来检查是否正确。

Just put this code in place of your blank if() 只需将这段代码替换为空白的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. 但我强烈建议您始终重命名文件,以免受到任何直接访问或损害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM