0

I am having trouble in managing images in a gallery. For example if abc.jpg is already exist. If i try to upload an image having the same name (abc.jpg) the previous image is replaced with new one . So i was thinking about renaming the image with a random number as image name (i.e current date+Time+Random Number). Here is my code

<?php
session_start();

include("includes/connect.php");
$name= $_SESSION['email'];
if (!isset($_FILES['image']['tmp_name'])) {
 echo "";
}else{
 $file=$_FILES['image']['tmp_name'];
 $image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
 $image_name= addslashes($_FILES['image']['name']);
   
 move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);
   
 $location="photos/" . $_FILES["image"]["name"];
   
 $pname=$_POST['p_name'];
 $email= $_SESSION['email'];
 $category=$_POST['category'];
 $dimention=$_POST['dimention'];
 $desc=$_POST['description'];
 $price=$_POST['price'];
 $status=$_POST['status'];
 $dop=$_POST['dou'];
 $save=mysql_query("insert into paintings (location,p_name,email,category,dimention,description,price,status,dou,varify) values ('$location','$pname','$email','$category','$dimention','$desc','$price','$status','$dop','0')")or die(mysql_error());
 $result= mysql_query ("select p_id from paintings ORDER BY p_id DESC LIMIT 1");
  
 $row=mysql_fetch_array($result);
 $pid=$row['p_id'];
 $save1=mysql_query("insert into upload (email,p_id,u_date) values ('$name','$pid',now())")or die(mysql_error());
 header('Location: user_profile.php');    
}
Ian
  • 24,116
  • 22
  • 58
  • 96

2 Answers2

1
$newfile=date('d-m-Y')."_".rand(0000,9999).$_FILES['image']['name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);

move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $newfile);
0
$filename=$_FILES["image"]["name"];    
$ext = explode('.', $filename);
$without_extension = substr($filename, 0, strrpos($filename, "."));

$final_name=$without_extension.time().'.'.$ext

This will work I guess there is no need for random number since we use unix timestamp. To make it simple

$filename=$_FILES["image"]["name"];
$final_name=time().$filename;
Gogul
  • 298
  • 2
  • 14