PHP Rename image while image uploading



Change image name while image uploading

In php we use file upload for uploading text file, image file and any document to our web application.
Some time we upload upload different image but the image name same at that time the old image replaced by last uploaded image.

Mostly in all social networking site all user upload their profile picture in account, what happens if some user upload same name image for profile picture. The last image displayed in both user profile picture, previous user profile picture replaced by new user profile picture.

To prevent above situation we need to rename the picture name while uploading, use some unique image name combination of unique userid with text..etc..

Rename Image name PHP Example

<html>
<head>
<title>PHP Reanme image example</title>
</head>
<body>

<form action="fileupload.php" enctype="multipart/form-data" method="post">
Select image :
<input type="file" name="file"><br/>
Enter image name :<input type="text" name="filename"><br/>
<input type="submit" value="Upload" name="Submit1">

</form>

<?php

if(isset($_POST['Submit1']))
{ 


$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$name = $_POST["filename"];

move_uploaded_file($_FILES["file"]["tmp_name"], $name.".".$extension);
echo "Old Image Name = ". $_FILES["file"]["name"]."<br/>";
echo "New Image Name = " . $name.".".$extension;

}


?>
</body>
</html>

The php example output is :

PHP file upload example
Rename image name while image upload

8 thoughts on “PHP Rename image while image uploading

  1. Mostly in all social networking site all user upload their profile picture in account, what happens if some user upload same name image for profile picture. The last image displayed in both user profile picture, previous user profile picture replaced by new user profile picture

    1. you have to use some unique identification for user. such as userID, profileID. While changing/uploading profile picture that time change imagename, join id with imagename and then upload. Each user profile picture uploaded with unique image name.

  2. Kindly tell me how to rename when file upload in database.
    like if file what i have uploaded name is IMG20180909122312.jpg
    and now i want to upload in databse with name of IMGJU18P001.jpg(some specific pattern)
    how to do it
    what you have told is just print two data only

  3. nice script but i want to save my file in “gallery” folder how i do this
    here dont set any folder image go to main folder

Leave a Reply to Meera Academy Cancel reply

Your email address will not be published. Required fields are marked *