0

How do i give the image a random name instead of taking the name the image currently have when being uploaded?

if(file_exists('folder/' . $_FILES['file']['name'])){
      echo "Change ImageName<br> ";

    } 
    else {
      move_uploaded_file($_FILES['file']['tmp_name'],'folder/' . $_FILES['file']['name']);
    $q = mysqli_query($con, "UPDATE users SET date=now(), image = '".$_FILES['file']['name']."' WHERE username= '$id'");

    }
anon
  • 237
  • 2
  • 11
  • http://stackoverflow.com/questions/48124/generating-pseudorandom-alpha-numeric-strings to help you make the name then replace $_FILES['file']['name'] with that plus '.jpg'; – Steve Nov 21 '15 at 23:00

2 Answers2

3

You can just use the uniqid to generate a unique file name if you don't care about original names.

$newFileName = uniqid('uploaded-', true) 
    . '.' . strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
move_uploaded_file($_FILES['file']['tmp_name'], 'folder/' . $newFileName);
$q = mysqli_query($con, "UPDATE users SET date=now(), image = '".$newFileName."' WHERE username= '$id'");
Constantine Poltyrev
  • 1,015
  • 10
  • 12
  • Thanks. How do i get a dot before the image type?(eg jpg) – anon Nov 21 '15 at 23:15
  • 1
    the call to pathinfo returns the file extension, so the file name will contain the proper extension, though I would add some contents check to ensure it really is an image. See the example snippet. – Constantine Poltyrev Nov 21 '15 at 23:18
1

See StackOverflow Generating (pseudo)random alpha-numeric strings to help you make the random name then replace $_FILES['file']['name'] with the newly generated name plus '.jpg';

Daniel's answer seems quite smooth to me.

Community
  • 1
  • 1
Steve
  • 808
  • 1
  • 9
  • 14