Delete files using PHP

Delete uploaded file in PHP using unlink() method.


We can delete files by providing the path to the file in sever. Unlink command work only if  write permissions given for the file.otherwise unlink command will get failed.


//path starting from default root directory
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
$path = "photos/wallpaper.jpg"; 

if(unlink($path)){
$msg = "deleted"; 
}else{
$msg = "cannot delete"; 
}
echo $msg;
?>

Sometimes we will get warning If either the file is not exists or due to write permissions not enabled.
To ignore the warning we can suppress by adding @ symbol 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
//path starting from default root directory
$path = "photos/wallpaper.jpg"; 

if(@unlink($path)){
$msg = "deleted"; 
}else{
$msg = "cannot delete"; 
}
echo $msg;
?>


No comments:

Post a Comment