DreaminMedia Queretaro
DreaminMedia Queretaro

Reputation: 229

Unique name for image before saving PHP

How do you set a unique name for the image? I'm trying to use tempnam() but it always saves the URL and the file as .tpm. Here is my code:

$file = $_FILES['file'];

$name = $file['name'];

$tname = tempnam("imagenes/", $name);

$path = "imagenes/" . basename($tname);
if (move_uploaded_file($file['tmp_name'], $path)) {
    // Move succeed.
} else {
    // Move failed. Possible duplicate?
}

$sql = mysql_query("INSERT INTO `productos` (`img`) VALUES ('".$path."')");
// ...

Also how do I check (for security) if the image has been really posted? Like mime type or something like that.

UPDATE:

I just fix unique name using

$tname =  uniqid().$name;

Upvotes: 0

Views: 201

Answers (2)

Mercurial
Mercurial

Reputation: 3885

To check for valid image and filesize,

$allowedExts = array("gif", "jpeg", "jpg", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| 
($_FILES["file"]["type"] == "image/jpeg")
||
($_FILES["file"]["type"] == "image/jpg")
||
($_FILES["file"]["type"] == "image/png"))
&&
($_FILES["file"]["size"] < 10485760)&& in_array($extension, $allowedExts))                {

    //DO
}

For unique image, i suggest you to store images in new table and append imade id as file name!

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157992

It's impossible to specify an extension using tempnam(). Unfortunately this is the truth.

While the problem you described sounds like an easy to resolve task, it's problematic to avoid possible race conditions (without using tempnam()). And although it is unlikely that they appear, the possibility remains.

If you are sure that only PHP works in that directory, you could implement a flock() based mechanism to ensure that a file will have be created only once.

If you don't care too much about that possible, but very unlikely, race conditions, I would advice you too use something like this:

$filename = 'images/' . uniqid() . '.jpg';

Upvotes: 1

Related Questions