【问题标题】:Error file_get_contents(): read of 8192 bytes failed with errno=21错误 file_get_contents(): 读取 8192 字节失败,errno=21
【发布时间】:2020-06-23 19:28:16
【问题描述】:

我有一个简单的脚本,它在每个子文件夹的每个文件中搜索给定的字符串。它工作得很好,直到我相信我的 PHP 得到了更新(我不太确定是不是因为这个)。这是代码:

<?php 
$limit = ini_get('memory_limit');
ini_set('memory_limit', -1);
ini_set('max_execution_time', 300);

function get_directory_content($directory){
    global $search, $results; 

    $files = scandir($directory);

    foreach ($files as $file) {
        if ($file == "." || $file == "..") {
            continue;
        }

        $is_file = false;
        $path = realpath($directory . DIRECTORY_SEPARATOR . $file);

        if (is_dir($path)) {
            get_directory_content($path);
            $is_file = true;
        }
        else{
            $is_file = true;
        }

        if ($is_file) {
            $content = file_get_contents($path);
        }


        if (stripos($content, $search) !== false) {
            $obj = new stdClass();
            $obj->dir = ($directory . DIRECTORY_SEPARATOR . "<b>".$file."</b>");
            $obj->file_name = $file;
            array_push($results, $obj);
        }
    }
}

if (isset($_GET["submit"])) {
    $search = $_GET["search"];
    $results = array();

    get_directory_content(dirname(__FILE__));
}

 ?>

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1>Main</h1>
        <form method="GET">
            <p>
                <input name="search" autocomplete="off" placeholder="Enter query here">
            </p>
            <input type="submit" name="submit">
        </form>


        <?php foreach ($results as $result):  ?>
            <h1><?php echo $result->file_name; ?></h1>
            <p><?php echo $result->dir; ?></p>
        <?php endforeach; ?>
</body>
</html>

我得到的错误是:注意:file_get_contents(): read of 8192 bytes failed with errno=21 Is a directory in /Users/nikolaynikolaev/Server/original_search.php on line 29

有人知道该问题的潜在解决方案吗?

如果您能帮助我解决问题,我将不胜感激。提前致谢! :)

【问题讨论】:

  • 这似乎是对递归函数的尝试,但它有几个错误的地方。您的直接问题是,在您检查if(is_dir($path)) 的情况下,您将$is_file 设置为true,而它应该为false。
  • 设置$path 后,您正在检查$path 是否是一个目录。如果是,您正在设置$is_file=true。这是故意的吗?因为$is_file 为真并且$path 指向目录,所以file_get_contents() 后面的几行可能正在目录上运行。
  • @ChrisHaas 说了什么。 :P
  • 哇!谢谢你们! @NikoNyman 和 ChrisHaas!我现在实际上正在学习,刚刚掌握了 C# 的窍门,但 PHP 仍然不是我的能力之一。这是一个非常愚蠢的错误,但多亏了你,我才能解决它。非常感谢你们! :)

标签: php file-get-contents errno


【解决方案1】:

通知消息用“是一个目录”清楚地解释它。

注意:file_get_contents(): read of [...] bytes failed with errno=21 Is a directory in [...]

要修复此错误,只需检查路径

foreach ($paths as $path) {
    if (!is_file($path))
        continue;
    
    // this path points to a file
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2020-12-04
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2021-04-10
    相关资源
    最近更新 更多