Generate unique name for file after upload

Asked

Viewed 1,872 times

1

Next, I have an upload form so that the user can post some images, and it is necessary that he is logged in to post, in each post the maximum number of images allowed is 5, I was following this idea to create the file name:

id_do_usuario_logged in - id_do_post + '__infix_'+ numero_da_image, would be something like that:

1-5_infixo_1.jpg

1-5_infixo_2.jpg

Where 1 is the login user id, 5 is the post id plus any other infix and the number would be generated by a repeat loop ,a foreach for example. The problem with this is that the post id will only be generated after the upload success so I could not use it to rename the file, as I can create a file with a unique name following a similar logic?

1 answer

1

If it’s just generating a unique name you can use md5 and uniqid plus the timestamp ex:

$novaimagem = md5(uniqid()) . '-' . time() . '.jpg';

// exemplo de saída: e9ec23688ceedd4039c527b898575126-1473293386.jpg

If you have to use your user id:

$novaimagem = $_SESSION['USER-ID'] . '-' . md5(uniqid()) . '-' . time() . '.jpg';

// exemplo de saída: userID-e9ec23688ceedd4039c527b898575126-1473293386.jpg

Note: if your user registration system already provides a logical sequence that will not repeat the id nor need to worry about the md5 beyond what timestamp is always sequential.

  • So the user id and the post are unique, but since I can’t use the post id before creating it I had to create otherwise, the timestamp takes the exact time it was created? year, month, day, hour, minutes and seconds?

  • 1

    I timed the answer because it returns a growing number (UNIX) so that your new file has the user id (will never save with another id) and the team that never repeated. You can read more about time in the PHP Handbook: http://php.net/manual/en/function.time.php. and if you want to go back to a timestamp use date to format: http://php.net/manual/en/function.date.php if the answer was helpful, indicate

Browser other questions tagged

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