Generate new name for image during upload - php

Asked

Viewed 1,844 times

1

I use the code below and it works correctly, but I need that during UPLOAD the image name is changed.

<?php require_once('conexao.php'); ?>
<?php
$cliente = $_GET['cliente'];
$cod = $_GET['cod'];

$uploaddir = "./clientes/".$cliente."/".$cod."/"; 

$file = $uploaddir . basename($_FILES['uploadfile']['name']); 

$imvfoto = $_FILES['uploadfile']['name'];       

$sqlgravar="INSERT INTO fotos(cod,cliente,foto) 
VALUES ('$cod','$cliente','$imvfoto')"; 
$resultadogravar = mysql_query($sqlgravar)
or die (mysql_error());



if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { 
  echo "success"; 
} else {
    echo "error";
}

    include("resize-class.php");
    $resizeObj = new resize("/home/roteirodoimovelc/public_html/cp/clientes/".$cliente."/".$cod."/".$imvfoto."");
    // *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
    $resizeObj -> resizeImage(600, 450, 'exact');
    $resizeObj -> saveImage("/home/roteirodoimovelc/public_html/cp/clientes/".$cliente."/".$cod."/".$imvfoto."", 100);

?>

How do I make this implementation so that the photo is renamed and saved to the server and also to the database?

4 answers

4


Just change these lines:

$file = $uploaddir . basename($_FILES['uploadfile']['name']); 
$imvfoto = $_FILES['uploadfile']['name'];

for

$imvfoto = "o nome que você quiser";
$file = $uploaddir . $imvfoto;

If you want to generate a unique ID and take the file extension:

$imvfoto = uniqid('img_').pathinfo($_FILES['uploadfile']['name'], PATHINFO_EXTENSION);
$file = $uploaddir . $imvfoto;

Of course you will adapt this to the desired logic, but as you did not define where the new name comes from in the question, it would be speculation.

Anyway, you need to see if this makes sense, because just using the bank ID as a new name, for example by filling in zeros. This would leave 0000001, 0000002, etc., even if you write the original name in the BD only as reference.

  • he doesn’t take the extension

  • The current example in the answer that generates a unique ID, and takes the extension.

3

You can use it UNIX TIMESTAMP

// Define o novo nome do arquivo usando um UNIX TIMESTAMP
$nome = time() . '.' . $extensao;

To catch the extension use:

$extensao= $_FILES['uploadfile']['type'];

3

Good Afternoon Gladison, when I work with image uploading in any language beyond the concern of changing the name I find it interesting you treat the extension so that there are no future problems with uploading files that could damage your server. This way I work the code this way.

        //verifica que tipo de arquivo esta sendo enviado
        preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $foto["name"], $ext);
        //altera o nome
        $nome_imagem = md5(uniqid(time())) . "." . $ext[1];
        //define o caminho para qual a imagem será enviada
        $caminho_imagem = "fotos/" . $nome_imagem;
        //efetua o upload
        move_uploaded_file($foto["tmp_name"], $caminho_imagem);

I hope I’ve helped.

  • Be good to the site Thiago.

  • Thank you very much Thiago, but this protection already use in Ajax that uses the photo for me.

  • 1

    @Gladisonneuzaperosini ajax does not protect anything because it can be edited by the client. Thiago’s solution is good, just remember to disable the mime/Magic If it’s Apache, then what counts is the content, not the extension. With mime/Magic on, Apache understands that an executable is executable even if the extension is . gif, for example. I’ve seen PHP hacking sent by CMS, with image extension. It went through the extension filter, but Apache ran as PHP. And the worst: mime/Magic comes ON as default in many installations.

  • 1

    I also believe that Ajax is very precarious in this protection, and yes for this function to be executed correctly you must configure Apache.

  • @Bacco thanks for the explanation! I will adjust the code.

  • It thinks without problems, it is an exit with considerable certainty, an improvement to the code. I am always adept at good suggestions :)

  • 1

    @Bacco one way that I’m using a lot nowadays is Codeigniter’s Encryption Class, where you can encrypt names, data and even parameters and then rescue them using your default key. If you are interested please follow the link below: https://ellislab.com/codeigniter/user-guide/libraries/encryption.html

Show 2 more comments

-1

This code below takes the extensions and gives a new name keeping the original extension.

$data = date("d-m-Y")."-";
    $id = $_REQUEST['id'];

     $Fotos = $_FILES['file'];
     $Nome    = $Fotos['name'];

    // Pega extensão do arquivo
            preg_match("/\.(gif|png|jpg|jpeg|bmp){1}$/i", $Nome, $ext);

            //  Retira a extensao do nome do arquivo
            $nome_sem_extensao = $Nome;
            $nome_sem_extensao = basename ($nome_sem_extensao,".gif");
            $nome_sem_extensao = basename ($nome_sem_extensao,".jpeg");
            $nome_sem_extensao = basename ($nome_sem_extensao,".jpg");
            $nome_sem_extensao = basename ($nome_sem_extensao,".png");
            $nome_sem_extensao = basename ($nome_sem_extensao,".bmp");

            //  Retira espaços em branco do nome do arquivo
            //$nome_banco = str_replace(" ","_",$nome_sem_extensao);

            //Gera um nome único para a imagem
            $novonomedaimagem = $data . md5(uniqid(time())) . "." . $ext[1];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.