简体   繁体   中英

How can i replace the image name and add date time and arandom number as image name using php

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 (ie 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'); } 

$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);
$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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM