Add uniqid() To String

I am trying to uniq to a string so the following code has:

	$n = "$imagename.$ext";

It creates a range and adds the file type such as: 19572185.png

Can anyone advise how I add uniqid() to a string.

case 'image/jpeg': $ext = 'jpg'; break;
case 'image/gif': $ext = 'gif'; break;
case 'image/png': $ext = 'png'; break;
case 'image/tiff': $ext = 'tif'; break;
default: 		$ext = ''; break;
}
if ($ext)
{
	$n = "uniqid().$ext";
	move_uploaded_file($_FILES['filename']['tmp_name'], $n);
	echo "Upload image '$name' as '$n':<br />";
}
else echo "'$name' is not accepted image file";
}
else echo "No image has been uploaded";

Howdy,
Just to understand what you are trying to do:
A user uploads a file.
If it is of an accepted type, you want to generate a unique name and rename it.
That correct?

Hi mate,

Its for an image upload, currently it only uploads one image and calls it image.png

I am trying to make it so it uploads infinite images each with a unique number.

Could you not then generate a unique file name based on the user’s IP address and the current time stamp?
Something like:

$n = time() . $_SERVER['REMOTE_ADDR'] . $ext;

The error in your code is because you have $n = “uniqid().$ext”; instead of $n = uniqid().“.$ext”;

Brilliant, thanks everyone. That worked straight away.

Just curious… If you try uploading a file type not in your case statement, does it error out saying nothing was uploaded, or does it try to go through the logic anyway? I ask because I thought that if($ext) check to see if it is set, while you would be setting an empty string to $ext.

Hi,

Yes I have this to only accept image files.

case 'image/jpeg': $ext = 'jpg'; break;
case 'image/gif': $ext = 'gif'; break;
case 'image/png': $ext = 'png'; break;
case 'image/tiff': $ext = 'tif'; break;
default: 		$ext = ''; break;
}
if ($ext)
{
	$n = uniqid().".$ext";
	move_uploaded_file($_FILES['filename']['tmp_name'], $n);
	echo "Upload image '$name' as '$n':<br />";
}
else echo "'$name' is not accepted image file";

Right, but if I’m not mistaken, even this line will cause if($ext) to return true:

default: $ext = ''; break;

Hi,

Not sure what you mean. When I try to upload a PHP file it rejects it.

Alright, I’m mistaken then :smiley:

No thats fine, thanks for checking.

When the code is up an running I need to through all the security holes so its good to discuss it.

It wouldn’t. You can use this chart to see what PHP would interpret it as.

Also this thread is a good read too.

ah thank you