Create and download file without saving on server

Description:

How to create a file on the server without saving it, just giving the user the possibility to open it or save it on the local machine?

Solution:

First, create the file contents as you would do normally. Then add the header attributes in which we specify the type of file.

Last, echo the contents of the file, which will take the header attributes and ask the user for saving the file.

Example creating a CSV file for download:

$fileContent = ”;
$fileContent .= “Id,First name,Last name\n”;
$fileContent .= “1,Jack,Doe\n”;
$fileContent .= “2,Jill,Jackson\n”;

header(“Content-type: application/csv”);
header(“Content-Disposition: attachment; filename=”output.csv”);
header(“Pragma: no-cache”);
header(“Expires: 0”);

echo $fileContent;

Advertisements

About admin

Just another php developer trying to give something back to the community.
This entry was posted in PhP, Tools and tagged , , . Bookmark the permalink.

4 Responses to Create and download file without saving on server

  1. vineeth says:

    Thanks a lot:-)……your article was very helpfull…..

  2. nothanks says:

    What could be causing this to not work? PHP configuration?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s