Home  >  Article  >  Backend Development  >  PHP function introduction—readfile(): output file content

PHP function introduction—readfile(): output file content

WBOY
WBOYOriginal
2023-07-25 12:44:071883browse

PHP function introduction—readfile(): Output file content

In PHP, the readfile() function is a very convenient function, which can be used to output the file content to a browser or file. The syntax of the readfile() function is as follows:

int readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] )

The readfile() function receives a file name as a parameter, reads the contents of the file and outputs it directly. The return value of this function is the number of bytes read, or false if the read fails.

Let’s look at an example below. Suppose we have a text file named data.txt. The content of the file is as follows:

Hello, World!
I am learning PHP.

Now, we want to convert the contents of the file through PHP code. output to the browser. We can use the readfile() function to implement this function. The sample code is as follows:

<?php
$file = 'data.txt'; // 文件路径

if (file_exists($file)) {
    header('Content-Disposition: attachment; filename=' . basename($file)); // 下载文件
    header('Content-type: text/plain'); // 设置文件类型为纯文本

    readfile($file); // 输出文件内容
} else {
    echo "File does not exist.";
}
?>

In the above code, we first check whether the file exists, and if it exists, set some HTTPs that need to be used when outputting the file. header, and then call the readfile() function to output the file contents.

When we run the above code, PHP will output the contents of the data.txt file and save it as the file data.txt.

In addition to outputting the file content to the browser, the readfile() function can also output the file content to other files. We only need to change the first parameter of the readfile() function to the path of the target file to be output. The sample code is as follows:

<?php
$sourceFile = 'data.txt'; // 数据源文件
$targetFile = 'output.txt'; // 输出文件

if (file_exists($sourceFile)) {
    readfile($sourceFile, $targetFile); // 将文件内容输出到目标文件中
} else {
    echo "File does not exist.";
}
?>

After running the above code, PHP will output the contents of the data.txt file to the output.txt file.

By using the readfile() function, we can easily output the file content to the browser or other files. Whether it is used for file downloading or file copying, the readfile() function is a very practical function.

The above is the detailed content of PHP function introduction—readfile(): output file content. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn