Creating Download Page with Countdown using PHP and JavaScript Tutorial

Introduction

In this tutorial, you will learn how to Create a File Download Page using PHP and JavaScript. The tutorial aims to provide a reference or guide to new programmers or students for handling files in terms of downloading them using PHP Language and JavaScript. This kind of feature is frequently used in a Content Management System whereas file download has a certain page that contains some information and a countdown before continuing the download process. Here, snippets and sample source codes are provided.

Getting Started

Since we will use PHP Scripts, we need to download and install software such as XAMPP/WAMP to run our PHP Scripts on our local machine. Next, compile some sample files to use for the sample application in a folder named uploads.

Coding Part

Now, we'll start the coding part of this tutorial.

Main Page

First, we will create the main page of the application. Create a new PHP File and save it as index.php. This file contains a combined PHP and HTML scripts for listing the list of files that are available. Using the scandir() method in PHP, we can list all the files of a directory. See the snippet below to understand more about this.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Download Countdown Page</title>
  8.  
  9.  
  10. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  11. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  12. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  13.  
  14. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  15. <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
  16. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
  17.  
  18. <style>
  19. html, body{
  20. min-height:100%;
  21. width:100%;
  22. }
  23. </style>
  24. </head>
  25. <body>
  26. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  27. <div class="container">
  28. <a class="navbar-brand" href="./">Download Countdown Page</a>
  29. <div>
  30. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  31. </div>
  32. </div>
  33. </nav>
  34. <div class="container px-5 my-3">
  35. <h2 class="text-center">Creating a File Download with Countdown Page using PHP and JavaScript</h2>
  36. <div class="row justify-content-center">
  37. <div class="col-lg-8 col-md-8 col-sm-12 mb-4">
  38. <div class="card shadow rounded-0">
  39. <div class="card-header rounded-0">
  40. <div class="d-flex justify-content-between">
  41. <div class="card-title flex-shrink-1 flex-grow-1">Files</div>
  42. </div>
  43. </div>
  44. <div class="card-body">
  45. <div class="container-fluid">
  46. <?php
  47. // Listing all files from a directory
  48. $files = scandir('uploads');
  49. ?>
  50. <!-- File List Container -->.
  51. <div class="list-group">
  52. <?php
  53. foreach($files as $file):
  54. // Skip return directories
  55. if(in_array($file, ['.', '..']))
  56. continue;
  57. ?>
  58. <div class="list-group-item list-group-item-action">
  59. <div class="d-flex justiy-content-between align-items-center">
  60. <div class="col-auto flex-shrink-1 flex-grow-1"><?= $file ?></div>
  61. <div class="col-auto">
  62. <a href="download.php?file=<?= $file ?>"><i class="fa-solid fa-download"></i></a>
  63. </div>
  64. </div>
  65. </div>
  66. <?php endforeach; ?>
  67. </div>
  68. <!-- End of File List Container -->
  69. </div>
  70. </div>
  71. </div>
  72. </div>
  73. </div>
  74. </div>
  75. </body>
  76. </html>

In the snippet above, I used CDNs for including the Bootstrap Framework for the design of the interface of the page. Each file listed contains a download anchor or link to redirect to the file download page. The below image is the sample output of the snippet.

PHP-JS File Download Page - Main Page

File Download Page

Then, we'll create the File Download Page using a PHP file extension. Save the file as download.php. The file contains the script for the display of the message and the countdown container before continuing to download the file.

  1. <?php
  2. $dir = "uploads/";
  3. $file = isset($_GET['file']) ? $_GET['file'] : '';
  4. // check file if exist
  5. if(!is_file($dir.$file)){
  6. echo "<script> alert(`The given file name does not exists.`); location.replace('./') </script>";
  7. }
  8. ?>
  9. <!DOCTYPE html>
  10. <html lang="en">
  11. <head>
  12. <meta charset="UTF-8">
  13. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  14. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  15. <title>Download Page</title>
  16.  
  17.  
  18. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  19. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  20. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  21.  
  22. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  23. <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
  24. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
  25.  
  26. <style>
  27. html, body{
  28. min-height:100%;
  29. width:100%;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  35. <div class="container">
  36. <a class="navbar-brand" href="./">Download Countdown Page</a>
  37. <div>
  38. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  39. </div>
  40. </div>
  41. </nav>
  42. <div class="container px-5 my-3">
  43. <h2 class="text-center">Download Page</h2>
  44. <hr>
  45. <div class="row justify-content-center">
  46. <div class="col-lg-8 col-md-8 col-sm-12 mb-4">
  47. <div class="card shadow rounded-0">
  48. <div class="card-body">
  49. <div class="container-fluid">
  50. <p>Downloading the <b><?= $file ?></b>.</p>
  51. <p>Please wait, file will be downloaded after <span id="countdown">10</span>s.</p>
  52. <p id="direct-link"></p>
  53. </div>
  54. </div>
  55. </div>
  56. </div>
  57. </div>
  58. </div>
  59. </body>
  60. </html>

Lastly, include the JavaScript below after the last child element of the document body. The script below creates a download anchor to the page but is not visible to the user. The download link will be triggered click after the countdown ends. It also generates a visible direct download link so users can download the file directly if ever some instances may occur while downloading the file automatically.

  1. <script>
  2. // File Link
  3. var link = `<?= $dir.$file ?>`
  4.  
  5. // Download link anchor
  6. var _anchor = document.createElement('a')
  7. _anchor.setAttribute("download", link)
  8. _anchor.setAttribute("href", link)
  9. _anchor.style['display'] = 'none'
  10. // _anchor.innerText = `< ?= $file ?>`
  11. document.querySelector('body').appendChild(_anchor)
  12.  
  13. //Get countdown starting number
  14. var countdown = document.getElementById('countdown').innerText
  15. countdown = new Number(countdown)
  16.  
  17. // Countdown Interval
  18. var cdInterval = setInterval(() => {
  19. countdown--;
  20. document.getElementById('countdown').innerText = countdown
  21.  
  22. /**
  23.   * Download Link and display Direct Download Link if Countdown ends
  24.   */
  25.  
  26. if(countdown == 0){
  27. clearInterval(cdInterval)
  28. // Tigger Download Link
  29. _anchor.click()
  30.  
  31. // Cloning the hidden download link
  32. var direct_link = _anchor.cloneNode(true)
  33.  
  34. // Changing the link display text
  35. direct_link.innerText = `Direct Link`
  36.  
  37. // Changing the link display to block [to be vissible]
  38. direct_link.style['display'] = 'block'
  39.  
  40. // Display direct link message
  41. document.getElementById('direct-link').innerHTML = 'If the file has failed to download, click the link to download the file directly.'
  42.  
  43. // Append direct link achor
  44. document.getElementById('direct-link').appendChild(direct_link)
  45. }
  46. }, 1000);
  47. </script>

Here's the sample snapshot for the output of the snippet above.

PHP-JS File Download Page - Download Page

There you go. You can now test the sample application on your end. The file will be automatically downloaded after (10) seconds. I have also downloaded the complete source code zip file I created for this tutorial and is free to download. The download button is located below this article.

DEMO VIDEO

That's it! I hope this File Download Page with Countdown using PHP and JavaScript Tutorial will help you with what you are looking for and that you'll find this useful for your current or future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment