PHP readfile() 如何处理 return 值

PHP readfile() how to handle return value

我正在学习 PHP 所以这是出于教育目的的问题。由于我无法在我使用的教程中找到答案,希望你能为我说清楚。

所以,假设我们有一个文件 "text.txt" 并且内容是:

"Hello World!"

以下 PHP 脚本:

<?php

echo readfile("text.txt");

?>

将输出 "Hello World!12" - 我想不出在任何情况下这样的输出都是有用的,但我发现如果我不想在最后看到文件长度,我' ve 省略 "echo":

<?php

readfile("text.txt");

?>

输出将是 "Hello World!"。这是一种更好的方法,但手册上说:"Returns the number of bytes read from the file.",所以我的问题是 - 我应该如何使用 readfile() 函数获取文件长度?根据我的逻辑,它 "returns" 文件内容,但我觉得我没有得到正确的东西。请帮我解决这个问题。

所以您想使用 readfile() 读取文件的大小?当然可以,但是这个函数也会输出文件。没什么大不了的,在这种情况下我们可以使用一些东西:output buffering.

<?php

ob_start();
$length = readfile("text.txt");
// the content of the file isn't lost as well, and you can manipulate it
$content = ob_get_clean();

echo $length;

?>

readfile 不是用来按照你写的方式获取文件大小或文件内容的。它通常用于向客户端发送文件。例如,假设您在客户端提交表单或单击某些 link 后在 Web 应用程序中创建了一个 pdf 文件。有时您可以将它们直接定向到文件,但有时出于某些原因(安全等)您不希望这样做。这样你就可以做到:

如何使用。

    $filepath = "../files/test.pdf";

    header("Content-Description: File Transfer");
    header("Content-Type: application/pdf; charset=UTF-8");
    header("Content-Disposition: inline; filename='test.pdf'");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($filepath));
    readfile($filepath);
    exit;

您可以使用它的示例。

    $filepath = "../files/test.pdf";

    ob_start();
    $filesize = readfile($filepath);
    $content = ob_get_clean();

    header("Content-Description: File Transfer");
    header("Content-Type: application/pdf; charset=UTF-8");
    header("Content-Disposition: inline; filename='test.pdf'");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $filesize );

    echo $content;

    exit;

所以,这里除了输出正确的文件头之外,还要输出文件内容,以便浏览器将其识别为pdf文件并打开它。