PHP重命名上传的文件(图片)

PHP重命名上传的文件(图片)

问题描述:

I want to rename the uploaded files. The names should be a random unique number.

Here is my upload script:

<?php
    if(isset($_POST["submit"])){
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);

        if(!($check == false)){
            if(file_exists($target_file)){
                $meldung = "Der Bildname exestiert bereits.";
            }
            if($_FILES["fileToUpload"]["size"] > 5242880){ /*Bytes*/
                $meldung = $meldung . "Das Bild ist zu groß.";
            }
            if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG") {
                $meldung = $meldung . "Ungültiges Format.";
            }

            if(!(empty($meldung))){
                $meldung = $meldung . "Die Datei wurde nicht hochgeladen.";
            }
            else{
                if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                    $picturename = $_FILES["fileToUpload"]["name"];
                    $pictureheightwidth = $check[3];
                    $picturepath = $target_file;
        
                    $eintrag = "INSERT INTO bilder (bild_name, bild_werte, bild_pfad) VALUES ('$picturename', '$pictureheightwidth', '$picturepath')";
                    $eintragen = mysqli_query($db, $eintrag);    
        
                    $meldung = "Das Bild wurde erfolgreich hochgeladen";
                }
                else{
                    $meldung = $meldung . "Fehler beim hochladen des Bildes.";
                }
            }
        }
        else{
            echo "Die Datei ist kein Bild.";
        }
    }
    echo $meldung;
?> 

<form action="index.php?content=upload" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" id="fileToUpload">
    <br>
    <input type="submit" value="Hochladen" class="button-submit" name="submit">
</form>

.........................................................................................................................................................................................................................

</div>

This can give you a clue on how to rename your file

http://php.net/manual/en/function.move-uploaded-file.php

You are looking for the uniqid() function:

$pictureame = uniqid(rand(), true);

It generates such a "random" id but, at the same time, also takes care that that unique name is not yet used by another file. Without that you would risk collisions. Not very likely at first sight, but that is just a question of scaling :-)

Take a look at the documentation: http://php.net/manual/en/function.uniqid.php