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.

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

报告相同问题?

悬赏问题

  • ¥15 ADS生成的微带线为什么是蓝色空心的
  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow
  • ¥15 densenet网络结构中,特征以cat方式复用后是怎么进行误差回传的
  • ¥15 STM32G471芯片spi设置了8位,总是发送16位
  • ¥15 R语言并行计算beta-NTI中tree文件的类型
  • ¥15 如何解读marsbar导出的ROI数据?
  • ¥20 求友友协助弄一下基于STC89C52单片机的声光控制灯原理图
  • ¥15 arduino双向交通灯设计
  • ¥15 有没有会粒子群算法的大能(○゜ε^○)求带不会出收敛图😭