Information



Tags



Share

How to avert the interference of extra HTML code on readfile in PHP

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement



Definition

In this tutorial, I will show you how to prevent the addition HTML code while using the readfile function in PHP. In that way, when a user downloads a page from your server as an output generated by the readfile function, do not get the following HTML code of that page.

Code

readfile() - Reads a file and writes it to the output buffer.

readfile() will not present any memory issues, even when sending large files, on its own.

Define the file path in the server and the file name.

Create headers - description, type, size, name - for the generated file.

Generate the file as an output by using the file name in the readfile function.

If the file created in the server temporarily, to delete the file without error, use ignore_user_abort(true) and unlink($file_path).

To avert any extra code addition coming from the server, use exit() function to break the code.


$file_path = "";
$file_name = "";

header('Content-Description: New File');
header('Content-Type: application/json');
header('Content-Length: ' . filesize($file_path));
header('Content-Disposition: attachment; filename="'.$file_name);
readfile($file_name);

ignore_user_abort(true);
unlink($file_path);
exit();