tonoslfx tonoslfx -5 years ago 232
PHP Question

php delete a single file in directory

I've got the php list directory script from this link
How do I delete a single file from the directoy? I tried

, but it deleted all the files from that directory. this the short code what i got from the link!

while ($file = readdir ($hDir)) {
if ( ($file != '.') && ($file != '..') && (substr($file, 0, 1) != '.') &&
(strtolower($file) != strtolower(substr($DescFile, -(strlen($file))))) &&
) {

array_push($FilesArray, array('FileName' => $file,
'IsDir' => is_dir($Directory.'/'.$file),
'FileSize' => filesize($Directory.'/'.$file),
'FileTime' => filemtime($Directory.'/'.$file)
$BaseDir = '../_cron/backup';
$Directory = $BaseDir;

foreach($FilesArray as $file) {
$FileLink = $Directory.'/'.$file['FileName'];
if ($OpenFileInNewTab) $LinkTarget = ' target="_blank"'; else $LinkTarget = '';
echo '<a href="'.$FileLink.'">'.$FileName.'</a>';
echo '<a href="'.unlink($FileLink).'"><img src="images/icons/delete.gif"></a></td>';

the list directory folder call : backup.

in the
, when i hover the link has change to another folder to admin folder?

Answer Source

unlink('path_to_filename'); will delete one file at a time.

If your whole files from directory is gone means you listed all files and deleted one by one in a loop.

Well you cannot de delete in the same page. You have to do with other page. create a page called deletepage.php which will contain script to delete and link to that page with 'file' as parameter.

foreach($FilesArray as $file)
    $FileLink = $Directory.'/'.$file['FileName'];

    if($OpenFileInNewTab) $LinkTarget = ' target="_blank"'; 
    else $LinkTarget = '';

    echo '<a href="'.$FileLink.'">'.$FileName.'</a>';
    echo '<a href="deletepage.php?file='.$fileName.'"><img src="images/icons/delete.gif"></a></td>';        

On the deletepage.php

//and also consider to check if the file exists as with the other guy suggested.
$filename = $_GET['file']; //get the filename
unlink('DIRNAME'.DIRECTORY_SEPARATOR.$filename); //delete it
header('location: backto prev'); //redirect back to the other page

If you don't want to navigate, then use ajax to make elegant.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download