10

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);

?>    
3
  • unlink( $dir."/".$data); Commented Nov 22, 2012 at 7:36
  • Check is correct path of file in mentioned Commented Nov 22, 2012 at 7:36
  • @Tahir Yasin Once i get answer I will accept Commented Nov 22, 2012 at 7:44

6 Answers 6

25

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);
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

3

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);

?>    

1 Comment

@xing are you sure your path is correct, because your php page directory should have "items" folder
3

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);

Comments

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

Comments

1

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.");

1 Comment

$variables are self explainatory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.