How to rename files dynamically in upload?

0

I have the following code and I do not know how to change it to dynamically rename the image at upload time.

PHP

<?php
$uploaddir = './fotos/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "Arquivo válido e enviado com sucesso.\n";
} else {
    echo "Possível ataque de upload de arquivo!\n";
}

echo 'Aqui está mais informações de debug:';
print_r($_FILES);

print "</pre>";
?>
    
asked by anonymous 25.07.2017 / 04:04

1 answer

1

You can use the md5 function along with [ microtime][2] to generate unique names for each image.

<?php

$currentName = $_FILES['userfile']['name'];
$parts = explode(".", $currentName);
$extension = array_pop($parts);

$newName = md5($currentName . microtime());
$destination = "./fotos/{$newName}.{$extension}";

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $destination)) {
    // ...
}

In this way, the new filename will be the result of the md5 of the current name concatenated with the return of microtime , making virtually any conflict between generated names impossible.     

25.07.2017 / 04:54