Welcome to W3Courses
 Like Us on Facebook

Delete File or an Image from the Server using PHP

If you want to delete a file or an image from the server via an interface from you website, you can use the following code

<?php

function deletemyfile($filename)
{

 $filearray = explode("/", $filename);

 $filecountno = count($filearray);
 $filecountno = $filecountno-1;
 for($i=0;$i<=$filecountno;$i++)
 {
  $myfilename = $filearray[$i];
 }

 if(file_exists("$filename"))
 {
  if(unlink("$filename"))
  {
   $deleteresult = "<b>".$myfilename."</b>: File was deleted successfully.";
  }
  else
  {
   $deleteresult = "<font color='red'><b>".$myfilename."</b>: Error! You may not have enough permission to delete this file.</font>";
  }
 }
 else
 {
  $deleteresult = "<font color='red'><b>".$myfilename."</b>: Error! Could not delete file. File does not exist.</font>";
 }
 return $deleteresult;
}

// Calling the function
$filename = '../photos/aaa.jpg';

$callresult = "<b>File Deletion Log:</b><br>";
$callresult = $callresult."<br>".deletemyfile($filename);
echo "$callresult";

?>

Share