In PHP, you may obtain a file from an online server utilizing the header()
perform to ship the suitable HTTP headers and the readfile()
or fread()
capabilities to learn and output the file’s content material. Right here’s a step-by-step information on easy methods to obtain a file in PHP:
- Create a PHP script to deal with the file obtain. Let’s name it
obtain.php
. - Be certain that the file you wish to obtain is situated in a listing accessible to your PHP script.
- In your
obtain.php
script, you may set the suitable headers to specify the content material kind, file identify, and the content material disposition to set off a file obtain immediate. Right here’s an instance:
// Examine if the file exists
if (file_exists($file_path)) {
// Set the suitable headers for the file obtain
header(‘Content material-Sort: utility/octet-stream’);
header(‘Content material-Disposition: attachment; filename=”‘ . basename($file_path) . ‘”‘);
header(‘Content material-Size: ‘ . filesize($file_path));
// Learn and output the file content material
readfile($file_path);
} else {
// File not discovered
echo “File not discovered.”;
}
?>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php // File path to the file you wish to obtain $file_path = ‘path/to/your/file.pdf’;
// Examine if the file exists if (file_exists($file_path)) { // Set the suitable headers for the file obtain header(‘Content material-Sort: utility/octet-stream’); header(‘Content material-Disposition: attachment; filename=”‘ . basename($file_path) . ‘”‘); header(‘Content material-Size: ‘ . filesize($file_path));
// Learn and output the file content material readfile($file_path); } else { // File not discovered echo “File not discovered.”; } ?> |
Exchange 'path/to/your/file.pdf'
with the precise path to the file you wish to obtain.
- Save the
obtain.php
script in your internet server. - Create a hyperlink or a button in your HTML web page that factors to the
obtain.php
script. For instance:
<a href=“https://phpgurukul.com/how-to-download-a-file-in-php/obtain.php”>Obtain File</a> |
When a person clicks on this hyperlink, the obtain.php
script will likely be executed, and the file will likely be prompted for obtain.
Just remember to have the required permissions and acceptable file paths arrange for the file you wish to obtain. Moreover, be sure that the file is throughout the internet server’s doc root or is accessible to your PHP script.