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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.