unlink - PHP: get content from first file in folder and then delete it -
using php, want content first file in folder , when content loaded, delete file. here have:
$a = opendir('./'); while (false !== ($entry = readdir($a))) { if($entry != '.' && $entry != '..') { echo $entry = file_get_contents('./'.$entry.'', file_use_include_path); break; // need first file } }
the code above loads first file in folder , can delete using like
unlink("temp.txt");
so there no permission denied errors. need delete file variable name (because every filename different). surprisingly me, unlink("$entry");
or similar not let me delete it, instead showing warning along first few lines of content of file. if echo $entry
shows temp.txt correctly. can enlighten me? missing here?
(optional (un)related question: if have numeric files 1.txt, 2.txt, 3.txt, 10.txt... . there way modify code above in way, not load files 1,10,2,3 ..., instead load 1,2,3,10...?)
update: updated code 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; // need first file } } unlink("./$entry");
the first problem you're overwriting $entry
file contents, such filename no longer valid when trying delete (explaining error file contents).
secondly, because you're using file_use_include_path
don't know file located, , unlink
resolves related current working directory, not $a
.
use unlink($a.'/'.$entry)
, you'll fine.
as unrelated question - use scandir
files in folder, apply natsort
resulting array sort 'natural sorting algorithm'. keep in mind directory listing lists folders .
, ..
you'll have detect , skip or remove manually.
Comments
Post a Comment