I have the following code to upload an image using a form. I have added a button to the form to use to remove the image, but I cannot figure out how to code the button to remove the users image. (memberFiles/$id.".jpg")

Here is my code to upload an image. I'd like to add code to remove an image. Any ideas?

<?php
session_start();
$id = $_SESSION['recid'];
$school = $_SESSION['college'];
// Process the form if it is submitted

if ($_FILES['uploadedfile']['tmp_name'] != "") {
    // Run error handling on the file
    // Set Max file size limit to 120kb
    $maxfilesize = 120000;
    // Check file size, if too large exit
    if($_FILES['uploadedfile']['size'] > $maxfilesize ) { 
        echo "Image too large.";
        unlink($_FILES['uploadedfile']['tmp_name']); 
        exit();
    // Check file extension to see if it is .jpg or .gif, if not exit
    } else if (!preg_match("/\.(gif|jpg)$/i", $_FILES['uploadedfile']['name'] ) ) {
        echo "Image not .gif or .jpg.";
        unlink($_FILES['uploadedfile']['tmp_name']);
        exit();
        // If no errors on the file process it and upload to server 
    } else { 
        // Rename the pic
        //Use the users numerical id to name the image file
        $newname = $id.".jpg";
        // Set the upload folder
        // Upload the file
        if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "memberFiles/".$newname)) {
           echo "Image uploaded.";
            exit();
        } else {
            echo "Upload error";
            exit();

        }
    } 
}
?>

You could use CSS display:none; or in HTML: <style="display:none;"> tag if you simply want to hide the image. I expect you're using a submit button to remove the image?

<?php
   if(isset($_POST['remove']))
   {
       ?>
             <div id="image" style="display:none;">
                  //image here
             </div>
       <?php
   }
   else
   {
        ?>
             <div id="image">
                  //image here
             </div>
        <?php
   }
?>

Otherwise, If you want to remove the image completely from the upload directory, you could maybe try using unlink()? Note:- I've not used this function before. Alternatively, you can delete a whole directory if necessary, by using rmdir()

<?php
   if(isset($_POST['remove']))
   {
       $File = "'memberFiles/'. $newname";
       unlink($File);
   }
?>

You may also want to delete the image path from the database if you're using one. Also make sure that users have the correct permissions to delete files from the server!

Just found this on the php man page:
"careful with unlink...
"very unlikely" is not "impossible" : granted, it will happen.

1) "expected" : a typo and you'll get : unlink('/')
2) "very likely" : some of your files are writeable by anyone.
3) "possible" : you're backup drive is mounted and preserves the authorizations of the original files
4) "very unlikely" : that particular day, at that particular moment, the unlink function decided to work recursively"

commented: Good advice, always. +1

I was trying to do it with unlink, and here's what I did with your suggestion, but my code breaks. What's wrong here? I'm not using a database to do this. I'm working directly with the server.

<?php
session_start();
$id = $_SESSION['recid'];
$school = $_SESSION['college'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
    // Run error handling on the file
    // Set Max file size limit to 120kb
    $maxfilesize = 120000;
    // Check file size, if too large exit
    if($_FILES['uploadedfile']['size'] > $maxfilesize ) { 
        echo "Image too large.";
        unlink($_FILES['uploadedfile']['tmp_name']); 
        exit();
    // Check file extension to see if it is .jpg or .gif, if not exit
    } else if (!preg_match("/\.(gif|jpg)$/i", $_FILES['uploadedfile']['name'] ) ) {
        echo "Image not .gif or .jpg.";
        unlink($_FILES['uploadedfile']['tmp_name']);
        exit();
        // If no errors on the file process it and upload to server 
    } else { 
        // Rename the pic
		//Use the users numerical id to name the image file
        // Set the upload folder
        // Upload the file
        if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "memberFiles/".$newname)) {
           echo "Image uploaded.";
            exit();
        } else {
            echo "Upload error";
            exit();
        }
    } 
				
		

		if(isset($_POST['remove']))
	{
   		$File = "'memberFiles/'".$newname"";
  	 	unlink($File);
	}	
			


}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
                  <table>
                    <form action="test.php" method="post" enctype="multipart/form-data" name="form" id="form" >
                    
                    <tr>
                      <td width="120"></td>
                      <td width="610" align="center"></td>
                      <td width="120" ></td>
                    </tr>
                    <tr>
                      <td></td>
                      <td><div align="center">
                          <input name="uploadedfile" type="file" />
                          &nbsp;&nbsp;&nbsp;
                          <input type="submit" name="Submit" value="Upload Image" />
                        </div></td>
                      <td></td>
                    </tr>
                      <tr>
                        <td width="120"></td>
                        <td width="610"><div align="center">
                            <input name="remove" type="hidden" />
                            <input type="submit" name="Submit" value="Remove Image" />
                          </div></td>
                      </tr>
                    </form>
                  </table>
</body>
</html>
<?php
session_start();
$id = $_SESSION['recid'];
$school = $_SESSION['college'];
// Process the form if it is submitted
if ($_FILES['uploadedfile']['tmp_name'] != "") {
    // Run error handling on the file
    // Set Max file size limit to 120kb
    $maxfilesize = 120000;
    // Check file size, if too large exit
    if($_FILES['uploadedfile']['size'] > $maxfilesize ) { 
        echo "Image too large.";
        unlink($_FILES['uploadedfile']['tmp_name']); 
        exit();
    // Check file extension to see if it is .jpg or .gif, if not exit
    } else if (!preg_match("/\.(gif|jpg)$/i", $_FILES['uploadedfile']['name'] ) ) {
        echo "Image not .gif or .jpg.";
        unlink($_FILES['uploadedfile']['tmp_name']);
        exit();
        // If no errors on the file process it and upload to server 
    } else { 
        // Rename the pic
		//Use the users numerical id to name the image file
        // Set the upload folder
        // Upload the file
        if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "memberFiles/".$newname)) {
           echo "Image uploaded.";
            exit();
        } else {
            echo "Upload error";
            exit();
        }
    } 
}

if(isset($_POST['remove']))
{
    $File = "'memberFiles/'".$newname"";
    unlink($File);
}	

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
                  <table>
                    <form action="test.php" method="post" enctype="multipart/form-data" name="form" id="form" >
                    
                    <tr>
                      <td width="120"></td>
                      <td width="610" align="center"></td>
                      <td width="120" ></td>
                    </tr>
                    <tr>
                      <td></td>
                      <td><div align="center">
                          <input name="uploadedfile" type="file" />
                          &nbsp;&nbsp;&nbsp;
                          <input type="submit" name="Submit" value="Upload Image" />
                        </div></td>
                      <td></td>
                    </tr>
                      <tr>
                        <td width="120"></td>
                        <td width="610"><div align="center">
                            <input name="remove" type="hidden" />
                            <input type="submit" name="remove" value="Remove Image" />
                          </div></td>
                      </tr>
                    </form>
                  </table>
</body>
</html>

Your remove button didn't have a unique name! I changed the name to 'remove'. Previously, you were checking to see if 'remove' was set, even though it didn't exist! Try this and let me know what happens.

I forgot to ask, is all of this code on one page? Or is your html form posting its contents to a different page (test.php)? If it's all one page, you need to change to form action to post its contents to itself using $_SERVER;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.