Hi guys.

So I have this code for uploading pictures for TinyMce. I can't figure out how I can manage random filenames on upload. I've tried to change "$filename" and adding time() and rand(), but it don't seem to change the filename.

Any ideas?

 define ("MAX_SIZE","200000");

 $errors=0;

 if(isset($_POST["submit"]))
 {
        $image =$_FILES["file"]["name"];
 $uploadedfile = $_FILES['file']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['file']['name']);
        $extension = getExtension($filename);
  $extension = strtolower($extension);
 if (($extension != "jpg") && ($extension != "jpeg") 
&& ($extension != "png") && ($extension != "gif")) 
  {
echo ' Unknown Image extension ';
$errors=1;
  }
 else
{
   $size=filesize($_FILES['file']['tmp_name']);

if ($size > MAX_SIZE*1024)
{
 echo "You have exceeded the size limit";
 $errors=1;
}

if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else 
{
$src = imagecreatefromgif($uploadedfile);
}

list($width,$height)=getimagesize($uploadedfile);

$newwidth=$_POST['width'];
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=$_POST['width'];
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
 $width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, 
$width,$height);

$filename = "../../../../../../../../bloggbilder/". $_FILES['file']['name'];
$filename2 = "http://-----.no/bloggbilder/". $_FILES['file']['name'];

imagejpeg($tmp,$filename,100);


imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}

On line 12 you assign a filename to $filename variable:

$filename = stripslashes($_FILES['file']['name']);

which is good. But then you do not use that variable on line 62:

$filename = "../../../../../../../../bloggbilder/". $_FILES['file']['name'];

which is strange since it defeats the purpose of the code on line 12. I think you should create a filename on line 12 and give it a random prefix or postfix, something like:

// create postfix
$postfix = '_' . date('YmdHis') . '_' . str_pad(rand(1,10000), 5, '0', STR_PAD_LEFT);
// get rid of slashes and add postfix
$filename = stripslashes($_FILES['file']['name']) . $postfix;
// handle the extension
...
// use the generated filename form now on
...

which will generate a filename like somename_20130416_005826.jpg

Thank you!

You are welcome, hopefuly it helps. Please mark thread as solved if there are no more questions. Happy coding.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.