New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home php codes How to force download file from server-PHP

How to force download file from server-PHP

How to force download file from server-PHP

Welcome back to, 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.


<!DOCTYPE html>
  <link rel="stylesheet" href="">
<script src=""></script>
<script src=""></script>
<script src=""></script>

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

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

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