• We just launched and are currently in beta. Join us as we build and grow the community.

How to Force Download File in PHP

yuhyuhyuh

Otaku Community Builder
Y Rep
0
0
0
Rep
0
Y Vouches
0
0
0
Vouches
0
Posts
73
Likes
171
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
If you are looking for how to Force Download File in PHP then you are at the right place. If you are going to download any file using PHP, you need a browser to force download the file without displaying it. We are going to show you how to download any file direct to the server in PHP. The example script that can be used for downloading the file in any types like image, text, document, zip file and pdf.

Check the Live Demo.

⚙ Live Demo

PHP Download Query

This query use to download a file in PHP. Copy and paste this query and save it as "download.php".

  1. <?php
  2. if

    (

    !

    empty

    (

    $_GET

    [

    'file'

    ]

    )

    )

    {
  3. $fileName

    =

    basename

    (

    $_GET

    [

    'file'

    ]

    )

    ;
  4. $filePath

    =

    'file_to_download/'

    .

    $downloadable_name

    ;
  5. if

    (

    !

    empty

    (

    $fileName

    )

    &&

    file_exists

    (

    $filePath

    )

    )

    {
  6. // Define headers
  7. header

    (

    "Cache-Control: public"

    )

    ;
  8. header

    (

    "Content-Description: File Transfer"

    )

    ;
  9. header

    (

    "Content-Disposition: attachment; filename=$downloadable_name

    "

    )

    ;
  10. header

    (

    "Content-Type: application/zip"

    )

    ;
  11. header

    (

    "Content-Transfer-Encoding: binary"

    )

    ;

  12. // Read the file
  13. readfile

    (

    $filePath

    )

    ;
  14. exit

    ;
  15. }

    else

    {
  16. echo

    'The file does not exist.'

    ;
  17. }
  18. }

Create Simple Markup and Download Button

This simple HTML source code where you can use the button to force download the file in PHP. Kindly copy and paste to the BODY tag of your web page.

  1. <h1

    >
  2. How to Force Download File in PHP
  3. </

    h1

    >
  4. <hr

    /

    >
  5. <br

    /

    >
  6. <a

    href

    =

    "download.php?file=sourcecodester.png"

    target

    =

    "_new"

    >
  7. <button

    class

    =

    "style_btn"

    >
  8. Dowload File
  9. </

    button

    >
  10. </

    a

    >
  11. <br

    /

    >
  12. <br

    /

    >
  13. <br

    /

    >
  14. <hr

    /

    >

  15. <a

    href

    =

    ""

    target

    =

    "_new"

    class

    =

    "free_source_code"

    >
  16. <h2

    >
  17. Free Source Code
  18. </

    h2

    >
  19. </

    a

    >

Output

2016-09-03_14_19_04-how_to_force_download_file_in_php.jpg


⚙ Live Demo

That's it, kindly click the "Download Code" button below for the full source code. Enjoy coding.


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,341

323,350

Top