We help IT Professionals succeed at work.

prepending images to existing images after image upload

Black Sulfur
Black Sulfur asked
Last Modified: 2019-03-30
I have an image uploader and picker in a modal. When uploading images, the actual file name should be prepended with mt_rand() in order to prevent duplicate file names. The php part of the below code works fine as when I check the directory they were uploaded to, the files all have random figures in front of the file name. The problem though is that after the upload is complete, it prepends those images to the images already displaying in the file picker and those file names don't have the mt_rand() applied which results in file not found errors in console.

So, if the file is called cat.jpg and I upload, the file in the uploads directory is 723672365273cat.jpg but the image prepended with the jQuery is just cat.jpg and obviously that cannot be found in the directory because it doesn't exist. I don't know how to solve this issue. Any help would be greatly appreciated.

The html form:

<form method="POST" enctype="multipart/form-data">
 <input type="file" name="file[]" data-method="ajax" accept="image/*" data-maxfilesize="5000000" multiple>

Open in new window

The jQuery:

var lastId;
                uploader_text: 'Drop files to upload, or',
                browse_text: 'Browse',
                only_one_error_text: 'Only one file allowed',
                not_allowed_error_text: 'File type is not allowed',
                big_file_before_error_text: 'Files, bigger than',
                big_file_after_error_text: 'is not allowed',
                allowed_before_error_text: 'Only',
                allowed_after_error_text: 'files allowed',
                browse_css_class: 'button button-primary',
                browse_css_selector: 'file_browse',
                uploader_icon: '<i class="pe-7s-cloud-upload"></i>',
                file_icon: '<i class="pe-7s-file"></i>',
                time_show_errors: 5,
                layout: 'thumbnails',
                method: 'normal',
                url: 'ajax_upload.php',
                delete_url: 'ajax_delete.php',

			$( "#drop_uploader_0" ).on( "file_upload_end", function( event, name) {

			var str = '<div class="col-md-3 img-box">';
			str += '<input type="checkbox" id="image_' + lastId +'" name="pics[]" value="' + name + '" data-id="image_' + lastId +'" checked/>';
			str += '<label for="image_' + lastId +'" style="background-image: url(uploads/' + name + ')">';
			str += '<i class="glyphicon glyphicon-ok"></i>';
			str += '</label>';
			str += '</div>';
			$( "#gallery-body" ).prepend(str);
			$( ".save" ).show();
			$( ".ajax" ).empty();

Open in new window

The below is the ajax_upload.php

if(isset($_FILES['file'])) {
    $name = mt_rand().$_FILES['file']['name'];
    $type = $_FILES['file']['type'];
    $size = $_FILES['file']['size'];

$uploaddir = 'uploads';

if(isset($_FILES['file']['name'])) {
    $new_name = mt_rand().$_FILES['file']['name'];
    $uploadfile = getcwd().DIRECTORY_SEPARATOR.$uploaddir.DIRECTORY_SEPARATOR.$new_name;
    if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
        // ok
        $file_id = md5($uploadfile);
        // Store File id in session. We can delete file by this id from other script
        $_SESSION["drop_uploader_".$file_id] = $uploadfile;
        $_SESSION["drop_uploader_".$file_id."_name"] = $new_name;
        $_SESSION["drop_uploader_".$file_id."_type"] = $_FILES['file']['type'];
        $_SESSION["drop_uploader_".$file_id."_size"] = $_FILES['file']['size'];
        $success_message = $file_id;
    } else {
        $error_message = "Error while uploading file ".$_FILES['file']['name'];

Open in new window

Watch Question

Distinguished Expert 2017

I suggest you in the server side (php) to check first if the name of the uploading file is exist at the directory.If exists then you have two choices.
1.Replacing the old with the new one (delete and write).
2. Sending an alert box at user to change the file name because it is already exists. At this case the upload procession is going to be abort.
Scott FellDeveloper
Most Valuable Expert 2013

Which jquery library are you using.

It looks like you not passing the $new_name though.

Personally, I wouldn't use a random number to make something unique. As a test, generate your random number 1000 times and see how many dupes you come up with.   It will be more than you thought.

If I am uploading an image that is tied to a database item, I may just use the database id in the file name in some fashion or look to see if the name is already on the server and if it is, then append a number, test to see if that is on the server and if not add 1 to the previous number until you have something unique. Or use your random approach, but just make sure to check that the file is not already on there and if it is, run another random number.

Confused...the images are uploading and being saved with the prepended data fine but you are displaying the images (or links to) in the browser but you don't know the name of the prepended file name?
Because I don't see anything wrong with the uploading code...
For ease of use why not just prepend the saved filename with the timestamp within jquery before the upload (kinda like what Scott is saying with uniqueness)


@ Scott, I am using jQuery 2.2.4, not sure if that is what you were asking?

Good point about the random number.

@ Nicholas, When the file is uploaded, it creates a new image name which I can see in the uploads folder. As mentioned if the original file I uploaded is cat.jpg, in the uploads folder it looks like 234523325cat.jpg for example. But, if I look in console at the prepended image, it still shows as cat.jpg

The problem is when I then insert data into the database it is saving that image as cat.jpg

So, when I go to the page that is meant to display these images they don't display because the actual file in the uploads folder is 234523325cat.jpg but the database record is cat.jpg
Scott FellDeveloper
Most Valuable Expert 2013

What I am getting at is it does not look like you are passing 234523325cat.jpg to the db.


@ Scott, I am passing the value of the checkbox to the database but it's the wrong name. It is the original file name instead of the new one.  I didn't include the code in the original question. Apologies.

I am doing it via ajax and the php code is:

$id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
foreach($_POST['pics'] as $pics) {
			$stmt = $link->prepare("INSERT INTO `accom_pics` (`accom_id`, `pic_name`) VALUES (?, ?)");
			$stmt->bind_param("is", $id, $pics);

Open in new window

Most Valuable Expert 2013
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)


Thanks Scott. Apologies for the delay. Will try that as soon as possible, just not able to right now...

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions