How to download file using php & javascript?

Member

by denis , in category: PHP General , 6 months ago

How to download file using php & javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 2 months ago

@denis 

To download a file using PHP and JavaScript, you can use a combination of server-side PHP code to fetch the file and client-side JavaScript code to trigger the download.


Here is an example of how you can achieve this:

  1. Create a PHP script to fetch the file from the server:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php
$file = 'path/to/your/file.pdf'; // Path to the file you want to download

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Length: ' . filesize($file));
    
    readfile($file);
    exit;
} else {
    echo 'File not found';
}
?>


  1. Create a JavaScript function to trigger the file download:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
function downloadFile() {
    fetch('download.php')
        .then(response => {
            if (!response.ok) {
                throw new Error('File not found');
            }
            return response.blob();
        })
        .then(blob => {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'file.pdf';
            a.click();
            URL.revokeObjectURL(url);
        })
        .catch(error => {
            console.error(error);
        });
}


  1. Call the downloadFile function when needed, such as on a button click:
1
<button onclick="downloadFile()">Download File</button>


Make sure to replace 'path/to/your/file.pdf' with the actual path to the file you want to download and 'file.pdf' with the desired name for the downloaded file.


This code snippet demonstrates a simple way to download a file using PHP and JavaScript, but you can customize it further based on your specific requirements.