dongwen7423 2013-08-28 11:41
浏览 167
已采纳

PHP:从文件夹中的第一个文件获取内容,然后将其删除

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");
  • 写回答

1条回答 默认 最新

  • droos02800 2013-08-28 11:43
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题