How to rename files dynamically in upload?

Asked

Viewed 315 times

0

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

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>";
?>
  • You know what your code does line by line?

  • @Andersoncarloswoss yes. I do. rss

  • @Andersoncarloswoss I have difficulty implementing md5 to generate random names for images.

  • So how do you think you change the file name?

  • @Andersoncarloswoss I believe capturing the file name, renaming and sending to the line move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile). Is that?

  • Exactly. If you look at documentation, the second parameter of move_uploaded_file is $destination, referring to the final file name. The name you give it here will be written to disk.

Show 2 more comments

1 answer

1


You can use the function md5 along with the [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)) {
    // ...
}

This way, the new file name will be the result of md5 of the current name concatenated with the return of microtime, preventing (practically) any conflict between the generated names.

Browser other questions tagged

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