how to delete a file from folder in php

xing picture xing · Nov 22, 2012 · Viewed 60.5k times · Source

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

?>    

Answer

Vamsi picture Vamsi · Nov 22, 2012

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