xing
xing

Reputation: 2453

how to delete a file from folder in php

I have a folder 'items' in which there are 3 files item1.txt, item2.txt and item3.txt. I want to delete item2.txt file from folder. I am using the below code but it not deleting a file from folder. Can any body help me in that.

<?php
        $data="item2.txt";
        $dir = "items";
        $dirHandle = opendir($dir);
        while ($file = readdir($dirHandle)) {
            if($file==$data) {
                unlink($file);
            }
        }

        closedir($dirHandle);

?>    

Upvotes: 10

Views: 83116

Answers (6)

Vamsi
Vamsi

Reputation: 873

Initially the folder should have 777 permissions

$data = "item2.txt";
$dir = "items";
while ($file = readdir($dirHandle)) {
    if ($file==$data) {
        unlink($dir.'/'.$file);
    }
}

or try

$path = $_SERVER['DOCUMENT_ROOT'].'items/item2.txt';
unlink($path);

Upvotes: 25

prabhu programmer
prabhu programmer

Reputation: 31

It's very simple:

$file='a.txt';

    if(unlink($file))
    {
        echo "file named $file has been deleted successfully";
    }
    else
    {
        echo "file is not deleted";
    }

//if file is in other folder then do as follows

unlink("foldername/".$file);

Upvotes: 3

Sibu
Sibu

Reputation: 4617

There is one bug in your code, you haven't given the correct path

<?php
        $data="item2.txt";    
        $dir = "items";    
        $dirHandle = opendir($dir);    
        while ($file = readdir($dirHandle)) {    
            if($file==$data) {
                unlink($dir."/".$file);//give correct path,
            }
        }    
        closedir($dirHandle);

?>    

Upvotes: 3

som
som

Reputation: 4656

if($file==$data) {
  unlink( $dir .'/'. $file);
}

Upvotes: 2

Tahir Yasin
Tahir Yasin

Reputation: 11709

No need of while loop here for just deleting a file, you have to pass path of that file to unlink() function, as shown below.

$file_to_delete = 'items/item2.txt';
unlink($file_to_delete);

Please read details of unlink() function

http://php.net/manual/en/function.unlink.php

Upvotes: 5

Louis Loudog Trottier
Louis Loudog Trottier

Reputation: 487

try renaming it to the trash or a temp folder that the server have access **UNLESS IT'S sensitive data.

rename($old, $new) or die("Unable to rename $old to $new.");

Upvotes: 1

Related Questions