-1

im using php to upload images to my site, i want to rename them as soon as they are uploaded and before they are placed in the server directory so that i can eliminate the chance of images being overwritten because of the name of the file, below is the code i have tried:

function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}

$uploaddir = 'tmp-uploads/';

$newFileName = generateRandomString(20);
rename($_FILES['userfile']['name'], $newFileName);

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

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    // do something else
}
Ryan Kelly
  • 163
  • 1
  • 2
  • 9

1 Answers1

0

$_FILES['userfile']['name'] is just a name in a variable it is not a file, if you want to change its value just use assignment.

$newFileName = generateRandomString(20);
$_FILES['userfile']['name'] = $newFileName;

or just use $newFileName instead of $_FILES['userfile']['name']

Musa
  • 96,336
  • 17
  • 118
  • 137