Jump to content

overwriting uploaded images in directory and database....


barbs75

Recommended Posts

Hi Guys,

 

I have a script which uploads images fine, and creates thumbnails easily too.

 

The only thing i am not sure of doing is overwriting these images.

 

What i want to do is, once a user has uploaded images, they are stored in a directory: 'Images/image1.jpg' like that, and the filename is then stored in my database to refer to.

 

But i want the user to be able to new images if they wish, which will overwrite the original images that they have? So overwriting the image that is already there with the new one, and if i can keep the filenames the same so that i don't have to change the data in the database!!

 

Whats the best way of doing this??

 

Do i have to delete the original images and then just post up the new ones? (using unlink()??) or is there a simpler way of doing this?

 

any help would be great!

 

cheers

 

Craig

Link to comment
Share on other sites

Can you explain a little bit what you wan't to do?

 

You want to allowe the user to choose which picture he want's to replace or you just want to let him replace the old image with a new one if it has the same filename????

 

Please, explain!!!

Link to comment
Share on other sites

Hey budimir,

 

The user when they upload a property, upload 3 images of their property. These are saved in a local directory and then the filename of the image and the created thumbnail are stored in a database table.

 

What i want to be able to do is allow the user to change the images they have uploaded. So they can upload 3 new images which will then overwrite the originals that were stored.

 

I have been doing some research, and i think the best way of doing this is having a function to delete the images that they are changing, and then just upload the new images as their 3 images...hence they will be replaced.

 

I have seen the unlink() function which deletes the file right? so i need collect the filenames of the images that are being replaced, delete them, and then just do a normal upload with the 3 images they want to upload as their new ones.....

 

does that make sense? is that the best way of going about it?

 

cheers

 

Craig

Link to comment
Share on other sites

Thats how I am doing it with the avatars for guys on my site.

 

Just curious, why 3 copies of what I am guessing is the same image? Why not use the same image specifying different dimensions for say a thumbnail and a full image using the height and width propertys of <img>

Link to comment
Share on other sites

hey kiwidave,

 

No, the 3 images are different, because i have a gallery for each property.

 

The thumbnail is created based on the original using imagecopyresampled() and set to dimensions that i have set..

 

cheers, i think i know how i am going to do it now....i think

 

cheers

 

Craig

Link to comment
Share on other sites

Just be aware, if every user's photos are stored in the same directory, and you don't rename the file upon upload, then there would be no way to stop two or more users from uploading different images with the same name and overwriting files from someone previous.

 

User a:

uploads: kitchen.jpg

-server stores file as kitchen.jpg

-db stores filename as kitchen.jpg

 

User b:

uploads: kitchen.jpg

-server overwrites kitchen.jpg

-db stores filename as kitchen.jpg

 

User b sees the right file with the right filename, user a sees the wrong file with the right filename.

Consider renaming the files uniquely or running a check on upload that looks for an existing file, and on true, renames the uploaded file accordingly

Link to comment
Share on other sites

hey mikeschroeder,

 

cheers for your help! what i do though is i re-name the uploaded image, using the users username and then retrieveing how many images they have uploaded by referring to 'num-uploads' field in my database which increments everytime the user uploads an image. The thumbs are doine the same way but have 'thumb_' infront of it, so i should have any problems with what you have suggested right?

 

The only thing i'm having problem i'm having is detecting which image is being changed to grab the filename to delete it? i don't know if you would know how to do this?

 

basically what i have at the moment, is the images that have been uploaded are displayed on screen, there is then a file upload file underneath where they select the image they want to replace it with and then the submit button for the form is clicked, and is processed on another php page.

 

I need to somehow detect which image is being replaced and then use that filename to retrieve it, and delete it...i can't think how i can do that without using JS or AJAX??

 

I was thinking of having a hidden field containing the image filename when the form is submitted, but there would be no way of detecting which image is being replaced....bit confusing...but do you get me??

 

any ideas?

 

Cheers

 

Craig

Link to comment
Share on other sites

actually,

 

thinkking about it, in my database i have the filenames stored and also have the house_id, username and user_id stored for each image. So i can refer to the filename by checking for images with the house_id (each house can only have 3 images) and username to pull the filenames.....

 

then use the filenames to check the directories and delete the images....

 

d'oh!!

 

but then it will remove all three, which i don't want because the user might only decide to change one of the images.....

 

really stumped here  ???

 

cheers

 

Craig

Link to comment
Share on other sites

You shouldn't have an issue with them being overwritten then.

 

When you display the upload form below the images, you could add a GET variable to the URL of the form, so when you submit the upload. It looks at that variable for which file to update.

 

Ex: action="upload.php?id=37"

 

then on upload look for an $_GET['id']  use that id value to determine which image to replace, only delete that one from the directory, and then update the database record accordingly.

 

hard to say exactly without seeing you table structure and what the html that provides the upload form looks like.

Link to comment
Share on other sites

Hey Mike,

 

Yeah, what you have suggested would work, but i want the user to be able to upload multiple images at a time, and i want the image to be deleted and replaced to be determined by the user choosing it?? which i wanted to do somehow with which inputfield the user selects an image on, determines which image is being replaced..

 

here is the php/html of the upload part:

                   <?php
					if ($function =='edit'){
				?> 
                    <table width="100%">
                        <tr>
                           <td colspan="3"><p class="largeblack">Below are thumbnail versions of the images you successfully uploaded to our server for your property image gallery:</p></td>
                        </tr>	
                        <tr>
                    <?php
						$sql = "SELECT * FROM images WHERE house_id = '$house_id'";
						$query = mysql_query($sql);

						while($data = mysql_fetch_assoc($query)){
								echo '<td align="center" width="33%"><img src="'.$data['thumbnail_filename'].'" alt="uploaded image" />';
								echo '</td>';
                            }	
					?>
                        </tr> 
                        </table>
                        <FORM ENCTYPE="multipart/form-data" action="stage3_process.php5?do=<?php echo $function?>&id=<?php echo $house_id?>" method="post">
                		<input type="hidden" name="MAX_FILE_SIZE" value="1100000" />	
                        <input type='hidden' name='stage' value='<?php echo $stage + 1 ?>'/>
					<input type="image" src="Images/upload.png" align="right" name="Send File" />
                    	<br />
                    	<br />
                        </FORM>
                        <?php
					}else{
					?>  	
                	<FORM ENCTYPE="multipart/form-data" action="stage3_process.php5" method="post">
                		<input type="hidden" name="MAX_FILE_SIZE" value="1100000" />
                        <div id="divinputfile">
                            <input class="open" name="userfile[]" type="file" size="60" id="userfile[]" />
                            <!--<div id="fakeinputfile"><input name="fakeuserfile" type="text" id="fakeuserfile" /></div>-->
                       </div>
                       <div id="divinputfile2">
                            <input name="userfile[]" type="file" size="60" id="userfile[]" />
                            <!--<div id="fakeinputfile2"><input name="fakeuserfile2" type="text" id="fakeuserfile2" /></div>-->
                       </div>
                       <div id="divinputfile3">
                            <input name="userfile[]" type="file" size="60" id="userfile[]" />
                            <!--<div id="fakeinputfile3"><input name="fakeuserfile3" type="text" id="fakeuserfile3" /></div>-->
                       </div>
                    	<br />
                        <input type='hidden' name='stage' value='<?php echo $stage + 1 ?>'/>
					<input type="image" src="Images/upload.png" align="right" name="Send File" />
                    	<br />
                    	<br />
              	   </FORM>
                   <?php }?>

 

Each of the upload fields when the user is not editing their property are stored in an array (userfile[]) these are then processed in a for loop.

 

For the editing i thought i could try and store the filename of each of the uploaded images on display in an array, which could correspond to the new filename inputfield number when posting it.....

 

so, the images that are already uploaded and displayed have the filenames:

pic 1: barbs1.jpg -- image[0]

pic 2: barbs2.jpg -- image[1]

pic 3: barbs3.jpg -- image[2]

 

then the inputfield id's for the inputfields displayed where the user can select an image to be replaced would look something like this:

 

image 1 replace: <input class="open" name="userfile[]" type="file" size="60" id="userfile[]" />

image 2 replace: <input class="open" name="userfile[]" type="file" size="60" id="userfile[]" />

image 3 replace: <input class="open" name="userfile[]" type="file" size="60" id="userfile[]" />

 

so what i was thinking of doing was if the user changed the first two images, then userfile[0] would correspond to image[0] and then userfile[1] would correspond to image[1].

 

But if the user changes image 1 and image 3 then image 3 is going to retrieve the wrong filename.....

 

thats why i thought i could use JS, as when the user clicks on the file upload window, the hidden field is generated, so then the image filename will only be posted for the images that are changed...

 

god really confusing....do you think that would work?

 

cheers

 

Craig

 

Link to comment
Share on other sites

Strictly on assumption, im going to assume you have two tables.

 

Images

  ImageID

  HouseID

  ...

 

-and-

 

Houses

  HouseID

  ...

 

when you build that form.

if you were to set it up in this way.

 

<form action="multip.php?house=[HouseID]" method="post" enctype="multipart/form-data" name="form1" id="form1">

    <input type="file" name="userFile[imageID]" id="fileField" /><br />

    <input type="file" name="userFile[imageID]" id="fileField2" /><br />

    <input type="file" name="userFile[imageID]" id="fileField3" /><br />

    <input type="submit" name="button" id="button" value="Submit" />

</form>

 

 

Array
(
    [userFile] => Array
        (
            [name] => Array
                (
                    [37] => filename1.jpg
                    [45] => filename2.jpg
                    [63] => filename3.jpg
                )

            [type] => Array
                (
                    [37] => application/download
                    [45] => application/download
                    [63] => application/download
                )

            [tmp_name] => Array
                (
                    [37] => C:\xampp\tmp\phpC68.tmp
                    [45] => C:\xampp\tmp\phpC69.tmp
                    [63] => C:\xampp\tmp\phpC6A.tmp
                )

            [error] => Array
                (
                    [37] => 0
                    [45] => 0
                    [63] => 0
                )

            [size] => Array
                (
                    [37] => 24091
                    [45] => 1066471
                    [63] => 30202
                )

        )

)

 

This assumes you have a HouseID specified in your post url and that instead of using userfile[] you used userfile[currentimageid]

When you go to process you know know that you only want to change images related to HouseID and that the

first file replaces imageID 37

the second file replaces imageID 45

the third file replaces imageID 64

 

a simple check on whether the name is blank or not, would be able to tell you if you need to do anything with that file upload box.

and you can parse over them with a foreach loop just as if they were named userfile[] the only diff will be that they wont be 0,1,2 they will be whatever id's that the current images are.

 

does that simplify it?

 

Mike

 

Link to comment
Share on other sites

Hey Mike,

 

Firstly thankyou for really helping me out here!

 

I get what you are doing with naming the inputfields with 'userfile[$image_id]' as then i can use the key of each array element to look up the image from the database where i can find the filename etc...

 

The only issue i am having is with iterating through the inputfiles.....

 

The steps which i think need to be taken are:

for each of the userfile array elements:

take the key of the element and retrieve the filename of the image

also take the image name of the image

check the directory for the filename, and if it exists delete it

do same for thumbnail

then, continue with normal upload and update database.

 

Is that right?!? i didnt really understand what was happening with the php you wrote on your last post? bit confused with that....

 

I am having problems iterating through each of the userfile post data

 

tried using a foreach loop as follows:

foreach($_POST['userfile'] as $key => $value){
	echo 'the value of the array usefile is'.$value;	
}

 

but i get PARSE ERRORS, it is obviously a two-dimensional array, so how do i loop through these post items??

 

cheers again

 

Craig

Link to comment
Share on other sites

Craig,

 

The php i provided was simply an array displaying what the $_FILES array would return after posting the form i provided.

 

You are trying to iterate over the $_POST array. Uploaded files go into the $_FILES global array.

 

//initialize a new file array
$files = array();
        //Loop over the userFiles array using the name
foreach($_FILES['userFile']['name'] as $key=>$value){
        //Make sure the uploaded file has a name
	if($value != ''){

		//go through the userFiles array and add them to the new $files array
		//use the $key value to gather that other values in the userFile array
		$files[$key] = array(
			'name'=>$value,
			'type'=>$_FILES['userFile']['type'][$key],
			'tmp_name'=>$_FILES['userFile']['tmp_name'][$key],
			'error'=>$_FILES['userFile']['error'][$key],
			'size'=>$_FILES['userFile']['size'][$key]			
		);

	}

}

//Display the new $files array	
print_r($files);

 

Take a stab  at this block of code.

Basically it uses the name array of userFile. and loops over it, breaking the array into $key and $value.

$key = id from the file upload script

$value = name of file.

 

if the $value isn't blank then we have a file upload.

so build a new array of uploaded files

 

This produces the following results when printing $files

Array
(
    [0] => Array
        (
            [name] => filename1.pdf
            [type] => application/pdf
            [tmp_name] => C:\xampp\tmp\php14E.tmp
            [error] => 0
            [size] => 24091
        )

    [1] => Array
        (
            [name] => filename2.pdf
            [type] => application/pdf
            [tmp_name] => C:\xampp\tmp\php14F.tmp
            [error] => 0
            [size] => 1066471
        )

    [2] => Array
        (
            [name] => filename3.pdf
            [type] => application/pdf
            [tmp_name] => C:\xampp\tmp\php150.tmp
            [error] => 0
            [size] => 30202
        )

)

 

This assumes your form does not use  userfile[$image_id]

if you setup your form as i suggest previously, then the array would contain keys that match your $image_id

 

Give it a shot let me know if you have any more questions.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.