PHP Read File
The PHP readfile()
function is used to read files and write its contents to the output buffer. This function outputs the contents of a file to the browser without needing to read the entire file into memory.
Syntax:
readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] ) : int|bool
Example:
$file = "example.txt";
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Output:
This function outputs the contents of a file to the browser.
Explanation:
The readfile()
function is an in-built PHP function that allows you to read the contents of a file and output it to the browser. It can be used to output images, PDFs, and other binary files.
This function also allows you to use HTTP headers to ensure the file is properly downloaded, and can be used to track the download in your server logs.
Use:
The readfile()
function can be used to read and output the contents of a file to the browser. It's commonly used to download files from the server, such as PDFs or images.
Important Points:
- The
readfile()
function is used to read and output the contents of a file to the browser. - This function can be used to download files from the server, such as PDFs or images.
- HTTP headers can be used to ensure the file is properly downloaded and can be tracked in server logs.
Summary:
The readfile()
function is a simple but useful function in PHP that allows you to read and output the contents of a file to the browser. It's commonly used to download files from the server, and HTTP headers can be used to ensure the file is properly downloaded.