Jump to content

Image upload questions...


phpnoobie9

Recommended Posts

I use the below script to upload images to the /images/i/ directory. I'm currently using wampserver2.

When I upload an image below it changes the name to a md5 name. Everytime I upload the same image with the same name it changes it to a different name. I'm guessing this md5 the temp name.

Will I have to worry about the image name ever being the same?

Whenever I upload the image it doesn't save the type of image. It just uploads it as a default file with no extension.

How do I write the uploaded image name to a database?

//Start image upload

//Check for an image
if (is_uploaded_file ($_FILES['image']['tmp_name'])) {
//Create new name
$newname = $_SERVER['DOCUMENT_ROOT'].'/images/i/'.md5($_FILES['image']['tmp_name']);
//Move image over
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname)) {
	echo '<p>Image uploaded!</p>';
	//Set $i to image name
	$i = $_FILES['image']['name'];
} else { 
	$errors[] = 'Could not move image';
	$newname = $_FILES['image']['tmp_name'];
}
} else {
$errors[] = 'No image uploaded';
}

//End image upload

Link to comment
https://forums.phpfreaks.com/topic/91489-image-upload-questions/
Share on other sites

I rewrote your script to this it uses the time()*rand(1,9999) instead of tmp_name this way it is almost impossible to get 2 the same

i also added a part to get the file extension will work even if the file has multiple "." in the name.

<?php
if (is_uploaded_file ($_FILES['image']['tmp_name'])) {
//Get file extension
$ext=explode('.',$_FILES['image']['name']);
$count=count($ext)-1;
$ext=$ext[$count];
//Create new name
$newname = $_SERVER['DOCUMENT_ROOT'].'/images/i/'.md5(time()*rand(1,99999).'.'.$ext);
//Move image over
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname)) {
	echo '<p>Image uploaded!</p>';
	//Set $i to image name
	$i = $_FILES['image']['name'];
	mysql_query('INSERT INTO `images` VALUES(\''.$i.'\')');
} else { 
	$errors[] = 'Could not move image';
	$newname = $_FILES['image']['tmp_name'];
}
} else {
$errors[] = 'No image uploaded';
}
?>

 

Scott.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.