Question

I'm making simple file uploading script right now. Everything works well, but when I upload another file with same - script just overwrites it. So, what I want is to be able rename each uploaded file to random name. (Ex. 12jfisfhassa .extension).

Here's what I have so far:

<html>
<head>
<title>File Uploader v1.0</title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<center>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<b>Please choose a file:</b><br/>
<input type="file" name="fileup"/><br/>
<br/>
<input type="submit" name='submit' value="Upload"/>
</tr>
</form>
</table>
</body>
</html>

<?php

$uploadpath = 'upload/';        // directory to store the uploaded files
$max_size = 103000000;          // maximum file size, in KiloBytes

$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png', 'rar', 'zip', 'exe');        // allowed extensions

if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
  $uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);               // gets the file name
  $sepext = explode('.', strtolower($_FILES['fileup']['name']));
  $type = end($sepext);       // gets extension
  list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);            // gets image width and height
  $err = '';         // to store the errors

  // Checks if the file has allowed type, size, width and height (for images)

  if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
  if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';

  // If no errors, upload the image, else, output the errors

  if($err == '') {
    if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
      echo '<font color="green"><b>Success!</b></font>';    
      echo '<br/>File: <b>'. basename( $_FILES['fileup']['name']). '</b>';
      echo '<br/>File type: <b>'. $_FILES['fileup']['type'] .'</b>';
      echo '<br />Size: <b>'. number_format($_FILES['fileup']['size']/1024, 3, '.', '') .'</b> KB';
      echo '<br/><br/>File path: <input type="text" value="http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), '\\/').'/'.$uploadpath.'" readonly>';
    }
    else echo '<b>Unable to upload the file.</b>';
  }
  else echo $err;
}
?>
</center>

And yeah, I don't use mysql. Please help? :)

Was it helpful?

Solution

Add this code and test it:

while(file_exists($uploadpath)){
  //get filename without suffix
  $rootname = basename($_FILES['fileup']['name'], $type);
 //add $i to the file name between rootname and extension (suffix)
 $uploadpath = "upload/".$rootname."-$i.".$type;
 $i++;
}

Add it like this:

  if($err == '') {
    $i = 1;
    while(file_exists($uploadpath)){
      //get filename without suffix
      $rootname = basename($_FILES['fileup']['name'], $type);
     $uploadpath = "upload/".$rootname."-$i.".$type;
     $i++;
    }
    if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
      echo '<font color="green"><b>Success!</b></font>';    
      echo '<br/>File: <b>'. basename( $_FILES['fileup']['name']). '</b>';
      echo '<br/>File type: <b>'. $_FILES['fileup']['type'] .'</b>';
      echo '<br />Size: <b>'. number_format($_FILES['fileup']['size']/1024, 3, '.', '') .'</b> KB';
      echo '<br/><br/>File path: <input type="text" value="http://'.$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['REQUEST_URI']), '\\/').'/'.$uploadpath.'" readonly>';
    }
    else echo '<b>Unable to upload the file.</b>';
  }

OTHER TIPS

    if(isset($_POST['submit'])){
        $newname=date('Ymdhis');
        $file1=$_FILES['file1']['name']=$newname.".jpg";
        $tmp_name=$_FILES['file1']['tmp_name'];
        $destination=__DIR__."\images\\";
        move_uploaded_file($tmp_name, $destination.$file1);
        echo "<pre>";
        print_r($_FILES);
    }
   //this is example is only for jpg you can check extension and can rename the same

You need to calculate a $uploadpath who is different from time to time. You could for instance combine the session-token with the current time in milliseconds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top