简体   繁体   中英

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.

$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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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