user203833
user203833

Reputation: 1

Rename file on uploading to Random name

I was wondering about the faster and the stronger way to rename a file to random ( Letters and Numbers )

Another issue is : I'm trying to put many NOT allowed type of files but actually my code is only work with one type !! So, if you may show me how I can put many types :)

This is my code:

   if ( $_REQUEST['do'] == "doUpload" )
{
  $TEMP = $_FILES['userfile']['name'];
  $FileName = stripslashes($TEMP);  
  $FileType = strrchr($FileName ,'.'); 

  $box = $uploadDIR.'/'.$TEMP;

$notype= ".php";

if ($FileType == $notype){

echo "NOT ALLOWED TO ATTACH THIS KIND OF TYPES";

exit;
}
  if (file_exists($box))
  {
    echo "<center><b><font color=red>THE FILE ALREADY EXIST</font><br><br><a href='http://$httpname/$box' target='_blank'>THE LINK</a></b><center>";
  }
  else
  {
    move_uploaded_file($_FILES['userfile']['tmp_name'],$box);

  echo " SUCCESS ";

Upvotes: 0

Views: 295

Answers (3)

Dave
Dave

Reputation: 3288

I work on an allow list rather than an exclusion list (there's more you don't want vs the ones you do want)

$allowedExtensions = array("txt","rtf","doc","pdf","docx","xlsx","xls","ppt","pptx","zip","rar","DOC","DOCX","mdb","MDB");

// check like this
if(!in_array($extension, $allowedExtensions)) {
    $adderr = "Invalid File Type. Please upload an allowed file type.";
}

For file naming I always go with a combination of the date with time stamp + the file name as if you just go with md5() of the file name as suggested above while its rare its still possible to get duplicates over a large enough dataset. By implementing the time protocol you never get duplicates.

$newname = md5(date("Y-m-d H:i:s").$_FILES['pricelist']['tmp_name'].$filename);

Upvotes: 0

Ivo Pereira
Ivo Pereira

Reputation: 3500

You could use uniqid():

$FileName = uniqid();  

Upvotes: 0

fullybaked
fullybaked

Reputation: 4127

To answer your disallowed file types I would do something like

$disallowedFileTypes = array('.php.', '.exe.', '.dmg');
if (in_array($FileType, $disallowedFiled)) {
    echo 'error';
    exit;
} else {
    // run upload
} 

Oh and the way you are checking for the extension is flawed as it would break if a file was uploaded with a . in the name eg my.file.php

It would be better to use the phpinfo() method http://php.net/manual/en/function.pathinfo.php

<?php
$path_parts = pathinfo($FileName);
$FileType = $path_parts['extension'];
?>

For random file names take a look at the PHP functions for exactly that

Upvotes: 1

Related Questions