How to force download file from server-PHP

0
325
download file using php

Welcome back to shortlearner.com, today in this post we will see how to force fully download a file from the server with the help of php.
In out previous post we learn how to import csv file into mysql database using php.

download file using php

so first of we need to understand overall scenario before downloading file from the server.
so i was created a image folder in a root directory of my project. there is a image file inside img folder with the name of test.jpg.

now we are writing a code for downloading this test image from the server without showing our img path to our end user because if we show our img folder in url than user can view all our images or files from the directory.

In the below code i am crating a index.php file which having a download button. so whenever user click on that button our download script will run and file will downloaded.

index.php

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</head>
<body>
<form method="post" action="#">
<button type="submit" name="download" class="btn btn-sm btn-success">Download File</button>
</form>
</body>
</html>

after click on the submit button we use the below code to download file from remote server to our system.

<?php if(isset($_POST['download'])){
$file = 'img/404.png';

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;
  }
} ?>

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error