Rename image when loading on PHP server

2

How about, I have a doubt maybe very basic but I can not find a code that works with mine.

What I want to do is save an image on my server (it already does) but that it is saved with a unique name and avoid duplicates

Here my code:

/*OBTENEMOS LOGO*/
    $imgA = $_FILES['img-af']['tmp_name'];
    $idUsu = $_POST['idUsu'];
    $establecimiento = new establecimiento();
    $destinoB="";
    $maxWidth=300; //ANCHO
    $maxHeight=300; //ALTO

    if ($imgA!="") {
        $destinoB = "logos/".$_FILES['img-af']['name'];
        $tamano = getimagesize($imgA);
        if($tamano[0] <= $maxWidth){
            if($tamano[1] <= $maxHeight){
                move_uploaded_file($imgA, $destinoB);
                $resultado = $establecimiento->cambiarLogo($idUsu,$destinoB);
                    if($resultado){
                        echo "OK";
                    }else {
                        echo "FAIL";
                    }
            }
        }
    }

Everything works fine, however when uploading an image with the same name it replaces it. I want to avoid that.

Thanks

    
asked by Dulce Méndez 03.10.2017 в 17:48
source

2 answers

3

Try generating a unique name with the uniqid function that generates a unique number.

You just have to concatenate the return value with the name of the image and you're done.

//..
if ($imgA!="") {
    $destinoB = "logos/". uniqid(rand(), true) .'_'.$_FILES['img-af']['name'];
    $tamano = getimagesize($imgA);
//..

It generates a long name but it will help you not to replace the images with the same name.

    
answered by 03.10.2017 в 18:01
0

You can generate a GUID for each file you upload.

function guid($p_corchetes) {//Genera una GUID Identificador Unico
    if (function_exists('com_create_guid')) {
        return com_create_guid();
    } else {
        mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45); // "-"
        $uuid = "";
        if ($p_corchetes == true) {
            $uuid = chr(123); //
        }
        $uuid = $uuid . substr($charid, 0, 8) . $hyphen
                . substr($charid, 8, 4) . $hyphen
                . substr($charid, 12, 4) . $hyphen
                . substr($charid, 16, 4) . $hyphen
                . substr($charid, 20, 12);

        if ($p_corchetes == true) {
            $uuid = $uuid . chr(125); //
        }

        return $uuid;
    }
}

$ name = guid (false);    echo 'GUID:'. $ name;

    
answered by 03.10.2017 в 18:26