dirdel.php:
<?php
//The name of the folder.
$dir = 'images';
//Get a list of all of the file names in the folder.
$arraydir = scandir($dir, 2);
print_r($arraydir);
//Loop through the file list.
foreach ($arraydir as $key => $value) {
unlink($arraydir[2]);
}
?>
Array outputs:
Array ( [0] => .
[1] => ..
[2] => ana.png
[3] => ban.png
[4] => ing.png
[5] => maca.png
[6] => no.png
[7] => pret.png )
Warning: unlink(ana.png): No such file or directory in C:\phpdesktop- chrome-57.0-rc-php-7.1.3\www\dirdel.php on line 10
To investigate the error, I also tried something like:
require 'images/';
Output:
Warning: require(C:\phpdesktop-chrome-57.0-rc-php-7.1.3\www\images): failed to open stream: Permission denied in C:\phpdesktop-chrome-57.0-rc- php-7.1.3\www\dirdel.php on line 2
I want to delete the file "ana.png" represented by: "$arraydir[2]" (the file is found in www/images)
I already searched in several places, but I did not find anything, that help me to fix this problem.
Is there any solution for this?
Alternatives are valid, as long as they respect the structure of the arrays:
Array ( [0] => .
[1] => ..
[2] => ana.png
[3] => ban.png
[4] => ing.png
[5] => maca.png
[6] => no.png
[7] => pret.png )
Thanks for your attention.
Actually if you run your code you'll always unlink only index 2 of your array. You have to make use of the variables and references that you are using in your foreach loop. I suggest you try the below mentioned code:
<?php
//The name of the folder.
$dir = 'images';
//Get a list of all of the file names in the folder.
$arraydir = scandir($dir, 2);
print_r($arraydir);
//Loop through the file list.
foreach ($arraydir as $key => $value) {
if ($arraydir[$key] == 'ana.png' && file_exists($dir . DIRECTORY_SEPARATOR . $arraydir[$key])) {
unlink($dir . DIRECTORY_SEPARATOR . $arraydir[$key]);
break;
}
}
?>
Hope this helps.