Home PHP How to force a CSV file to download when clicking on a download link using PHP?
 
 
 

How to force a CSV file to download when clicking on a download link using PHP?

PDF Print E-mail

Question: How to force a CSV file to download when clicking on a download link using PHP?

Example: We have a CSV file called example.csv we want users to download to use as a template. Now some browsers will display the contents of the file instead of asking users to download the file. What we want to do is to force the download instead of displaying the contents in the browser.

 

Answer:

  • Create a new PHP file called 'download.php'
  • Open the file for editing
  • Copy the code below into the 'download.php' file
    header('Content-Type: application/csv'); //Outputting the file as a csv file
    header('Content-Disposition: attachment; filename=example.csv'); //Defining the name of the file and suggesting the browser to offer a 'Save to disk ' option
    header('Pragma: no-cache');
    
    echo readfile('example.csv'); //Reading the contents of the file
    
  • Now on the page where you want the user to click on the link to download the file add the following code
    <a href="download.php">Click here to download an example of the "CSV" file</a>
    
  • Now everytime the user clicks on the link the browser won't display the contents but will offer to download the fileĀ 
+/-
  • Sahil - Not Working
    Buddy i want to tell you that code you are refferin is downlodin the
    download.php. bt want a csv file to get download so now what to do??[color=blue]
    [/color]
  • TechPortal - @Sahil
    The code works, you must be doing something wrong. Could you maybe post your
    code and how you call the download.php file?
+/- Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
Security Please input the anti-spam code that you can read in the image.
 

Go Daddy $7.49 .com Sale!