Jump to content

Uploading image and deleting old image


oraya

Recommended Posts

Could someone show me how I may edit my update script to delete the old image and replace it with the new image uploaded?  So if they decide to change the image by uploading a new one, the old image file will be deleted  off the server at the same time.  For the life of me I can't figure it out.  I'm not sure how to write the if statement.

 

Oraya

 

 

Submission Form:

 

<form action="includes/update.php" method="post">
<fieldset class="form_fieldset">
<legend> Update - <?php echo $title;?> </legend>

<input type="hidden" name="id" value="<?php echo $id;?>" />
<input type="hidden" name="redirect" value="welcome.php" />
<input type="hidden" name="location" value="<?php echo $location; ?>" />
<input type="hidden" name="table" value="<?php echo $table;?>" />
<input type="hidden" name="message" value="Welcome Message Updated Successfully!!" />
<input type="hidden" name="redirect" value="welcome.php" />

<label>Select File:</label><input name="uploadedfile" type="file" class="form_input" />
<label>Select Image Position:</label><select class="select" size="1" name="position">
<option value="left">Left</option>
<option value="right">Right</option>
</select>

<label>Image:</label><input type="text" class="image_input" value="<?php echo $image;?>" />
<div><label>Subtitle:</label><input class="input" type="text" name="sub_title" value="<?php echo $sub_title;?>" /></div>
<label>Content:</label>
<br />
<textarea wrap="physical" id="form_textarea" class="widgEditor nothing"><?php echo $content;?></textarea>
<br />
<input type="submit" value=" Update Content " class="form_submit"/>
</fieldset>
</form>

 

 

The Update Script:

 

<?php
$location = mysql_real_escape_string( $_POST["location"] );
$target_path = $location;
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

$host = "localhost"; 
$user = "myusername"; 
$pass = "mypassword";
$database = "mydatabase";

$conn = mysql_connect($host, $user, $pass) or die( mysql_error() );
        mysql_select_db($database) or die( mysql_error() );

$table = mysql_real_escape_string( $_POST["table"] );
$message = mysql_real_escape_string( $_POST["message"] );
$redirect =mysql_real_escape_string($_POST['redirect'] );
$position = mysql_real_escape_string( $_POST["position"] );
$sub_title = mysql_real_escape_string( $_POST["sub_title"] );
$content = mysql_real_escape_string( $_POST["content"] );
$image = basename( $_FILES['uploadedfile']['name'] );

$sql="INSERT INTO $table SET location=$location, image=$image, position=$position, sub_title='$sub_title', content='$content'";


$result = mysql_query( $sql ) or die( mysql_error() );

if($result)
{
     header("Location: ../successful.php?message=$message&redirect=$redirect");
}}else{
     echo"there was a problem!";
}
mysql_close($conn);
?>

Link to comment
Share on other sites

Well, it depends . . .

 

Are you wanting the user to upload another file of the same name to overwrite the original? If so, move_uploaded_file() will do that automatically. But, the problem comes with the query whether or not the user has uploaded a new file with the same or different name.

 

I can't discern any unique field from your query. Typically I would expect to see a user_id or something that would associate the record in some way to be unique. If you DO have a unique field in that query AND it is set as unique in that table then you can use the ON DUPLICATE KEY UPDATE clause in your query.

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
  ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

 

So, if the record being added would cause a conflict on a unique column the existing record would be updated. But, what about the original image (if the new one has a different name)? You would likely want to delete that image. That is why you usually see images renamed according to the unique key (e.g. user images may be named per the user ID).

 

So, I can't really provide a meaningful solution because there are too many unanswered questions. You can either take the suggestions given and build your solution or provide more details.

Link to comment
Share on other sites

I thought about that, but not sure how to go about it.  Would it be ok if I came back in a little while with some more questions?  I'm just setting up a test site and test database for this purpose.

 

Oraya.

Link to comment
Share on other sites

Ok just to follow this up, for anyone else that is looking for something similar, I've figured it out.  This is what I did, I placed a check box on the update form named replace.  I then used an if statement to see if the checkbox is set first in the update php,  if it is then it deletes the file and then proceeds with the upload of the new file.

 

 

UPDATE FORM

 

<?php
$dbhost = 'localhost';
$username="";
$password="";
$database="test";

mysql_connect($dbhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
// Retrieve data from database
$query="SELECT * FROM images";
$result=mysql_query($query);
$num=mysql_numrows($result);
$table = 'images';
$title = "TESTING FILE DELETE";

$i=0;
while ($i < $num) {

$id=mysql_result($result,$i,"id");
$image=mysql_result($result,$i,"image");
$location=mysql_result($result,$i,"location");
$position=mysql_result($result,$i,"position");
$content=mysql_result($result,$i,"content");
?>


<form enctype="multipart/form-data" action="insert.php" method="post">
<fieldset class="form_fieldset">
<legend> <?php echo $title;?> </legend>

<input type="text" name="id" value="<?php echo $id;?>" size="1" />
<input type="text" name="location" value="images/" />
<input type="text" name="table" value="<?php echo $table;?>" />

<div><label>Image:</label><input type="text" name="image" class="image_input" value="<?php echo $image;?>" /></div>

<div><label>Select File:</label><input name="uploadedfile" type="file" class="form_input" /></div>

<div><label>Do you wish to replace the image with new one?: </label><input type="checkbox" name="replace" value="Yes" /></div>
<div><label>Select Image Position:</label><select class="select" size="1" name="position">
<option value="left">Left</option>
<option value="right">Right</option>
</select></div>

<br />
<div><label>Content:</label><textarea wrap="physical" cols="100" rows="20" name="content" id="form_textarea"><?php echo $content;?></textarea></div>
<br />
<input type="submit" value=" Update Content " class="form_submit"/>
</fieldset>
</form>

<?php
$i++;
}
mysql_close()
?>

 

UPDATE SCRIPT

 

<?php
$host = "localhost"; 
$user = ""; 
$pass = "";
$database = "test";

$replace = mysql_real_escape_string( $_POST["replace"] );
$image = mysql_real_escape_string( $_POST["image"] );
$location = mysql_real_escape_string( $_POST["location"] );
$target_path = $location ;

if (isset($_POST['replace'])){
    unlink($location . $image);
} else {
    echo 'delete file did not work!';
}


$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {

$host = "localhost"; 
$user = "penfal"; 
$pass = "bluenote";
$database = "test";

$conn = mysql_connect($host, $user, $pass) or die( mysql_error() );
        mysql_select_db($database) or die( mysql_error() );

$id = mysql_real_escape_string( $_POST["id"] );
$table = mysql_real_escape_string( $_POST["table"] );
$image = mysql_real_escape_string( $_POST["image"] );
$location = mysql_real_escape_string( $_POST["location"] );
$position = mysql_real_escape_string( $_POST["position"] );
$content = mysql_real_escape_string( $_POST["content"] );
$image = basename( $_FILES['uploadedfile']['name'] );

$sql="UPDATE $table SET location='$location', image='$image', position='$position', content='$content' WHERE id='$id'";


$result = mysql_query( $sql ) or die( mysql_error() );

mysql_close($conn);
if($result)
{
     echo"it worked!!";
}}else{
     echo "ERROR";
}


?>

Link to comment
Share on other sites

What you have really doesn't make sense. The "replace" checkbox is only deleting the existing image of the same name. The move_uploaded_file() would do that anyway. So, if someone uploads an image with the same name, but does not check the replace checkbox, the image will still get replaced. But, even if the user does check that checkbox you are still going to end up with a duplicate entry in the database. So, the checkbox serves no purpose.

 

Based upon what you have done it seems you are only wanting to update the image IF it has the same name. So, a better solution would be this:

 

Don't use a "replace" checkbox. Instead, just check if the image already exists to determine whether you should insert a new record or not when you get tot he Query part. Also, there are other problems. For example, you are using mysql_real_escape_string() on the values to use in the file operations. That could cause errors. Use mysql_real_escape_string() for string data WHEN it is being used in the query. You should validate data for file operations differently.

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.