Renaming images with an AUTO ID name using PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pinch
Forum Newbie
Posts: 1
Joined: Sat Mar 21, 2009 5:34 am

Renaming images with an AUTO ID name using PHP

Post by pinch »

Hey guys im pretty new to php and i am making a very basic upload and delete image editor for my boss so he can upload photos of his products and give them descriptions for his website. I have it working pefectly but now i notice that if you upload more than one of the same file name then they automatically overwrite each other. I was wondering if there is any sort of codes i can put in so that i could rename the file with my database created auto incremental ID and then change photoname itself and the file name in the database if that makes sense? here is the code i am using.

<?php

//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$pic=($_FILES['photo']['name']);

// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("db_users") or die(mysql_error()) ;
$randName = md5(rand() * time());
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ;

//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
User avatar
jaoudestudios
DevNet Resident
Posts: 1483
Joined: Wed Jun 18, 2008 8:32 am
Location: Surrey

Re: Renaming images with an AUTO ID name using PHP

Post by jaoudestudios »

When you move the temp file to the location with the original filename, just create your own filename. This is usually done with the primary key in the database (auto increment), therefore it is always unique and then the rest of the row information in the database can be information on the image, i.e when it was upload, who uploaded it, alt tag etc...
Post Reply