Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding random number to uploaded file in PHP

I have my upload php code where my intent is , obtained file from $_files, add a random number between 0 and 9999 to the name of image like this:

image sent : image.jpg
before saving : image321.jpg

the image is saved in my upload folder but the filename are like "php2983204tmp"

if ($file !== null) {
    $rand = rand(0000,9999);
    $path = "some_path";

    $file_name = $file->getClientOriginalName(); // file
    $extension = $file->getClientOriginalExtension(); // jpg

    $file->move($path, $file_name.$rand.$extension);

    $response = "File loaded successfully: " . $file_name.$extension;
    $response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';

    return new Response($response);

any ideas to fix?

like image 279
Fedeco Avatar asked Feb 03 '26 09:02

Fedeco


1 Answers

The filename in your example is php and your extension is tmp. None of them have the . that you are missing.

You need to add the dot . as a string after the $file_name and $rand, before the $extension like this:

$file->move($path, $file_name.$rand. "." .$extension);
like image 94
Daniel Dudas Avatar answered Feb 05 '26 21:02

Daniel Dudas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!