4

How to rename the file of image before inserting into database?

  • DB name :Project
  • Table Name: image
  • ields: id (int), file (varchar) [image url stored here], name (varchar) [image description]

HTML Codes GOES HERE

<form method="POST" action="signup_process.php" enctype="multipart/form-data">
 Image:  <input type="file" name="user_image">
<input tyoe="submit" value="submit">
 </form>

signup_process.php

 <?php
    include 'dbcon.php';
    $filename = $_FILES[user_image][name];
    $source = $_FILES[customer_photo][tmp_name];
    $destination = "photos/$filename";
    move_uploaded_file($source, $destination);

//sql statement bla bla below to upload file in image table

    ?>

This script upload the file in photos directory of my seerver but what i want is i want to change that name to corresponding id of my image table . for example sunshine.jpg --> 5.jpg

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
rajkumar
  • 365
  • 5
  • 10

2 Answers2

1
Please Check below code ,is working for me.

$source = $_FILES[customer_photo][tmp_name];
$temp = explode(".",$_FILES["user_image"]["name"]);
$newfilename = rand(1,99999) . '.' .end($temp); //you can change here random id replace the your id
$destination = "photos/$newfilename";    
move_uploaded_file($source, $destination);
shashik493
  • 790
  • 1
  • 10
  • 12
1

If you want to change the file name before moving it to it's final location, simply change this line:

$destination = "photos/$filename";

to this:

$path_parts = pathinfo($_FILES["user_image"]["name"]);
$extension = $path_parts['extension'];
$destination = "photos/<the name you want>." . $extension;