Reputation: 31
Using PHP, I want to get the content from the first file in a folder and when the content is loaded, delete the file. Here is what I have:
$a = opendir('./');
while (false !== ($entry = readdir($a))) {
if($entry != '.' && $entry != '..') {
echo $entry = file_get_contents('./'.$entry.'', FILE_USE_INCLUDE_PATH);
break; // only need the first file
}
}
The code above loads the first file in the folder and I can delete it successfully using something like
unlink("temp.txt");
So there are no permission denied errors. BUT what I need to do is delete the file by its variable name (because every filename is different). Surprisingly for me, unlink("$entry");
or something similar does not let me delete it, instead showing a warning along with the first few lines of the content of that file. If I echo $entry
It shows temp.txt correctly. Can someone enlighten me? What am I missing here?
(Optional (un)related question: If I have numeric files like 1.txt, 2.txt, 3.txt, 10.txt... . Is there a way I could modify the code above in a way, that it does not load files like 1,10,2,3 ..., instead load it like 1,2,3,10...?)
UPDATE: The updated code that works (for future reference):
$a = opendir('./');
while (false !== ($entry = readdir($a))) {
if($entry != '.' && $entry != '..') {
echo $b = file_get_contents('./'.$entry.'', FILE_USE_INCLUDE_PATH);
break; // only need the first file
}
}
unlink("./$entry");
Upvotes: 0
Views: 421
Reputation: 41958
The first problem is that you're overwriting $entry
with the file contents, as such the filename is no longer valid when trying to delete it (explaining the error with the file contents).
Secondly, because you're using FILE_USE_INCLUDE_PATH
you don't know exactly where the file is located, and unlink
resolves related to the current working directory, which is most probably not $a
.
Use unlink($a.'/'.$entry)
and you'll be fine.
As for the unrelated question - use scandir
to get all the files in the folder, then apply natsort
to the resulting array to sort by a 'natural sorting algorithm'. Keep in mind that a directory listing always also lists the folders .
and ..
which you'll have to detect and skip or remove manually.
Upvotes: 2