PHP: Code to download a file

Hello friends,
In last week I had a requirement to give links of files to user. And if user will click on that file’s link then that file will be downloaded to his/her PC.
To satisfy the above requirement I had searched the web and found many solutions for that. But our site is in PHP language, so all the solutions were not valid for me. Where at last I found a good PHP code to download a file and here I want to share that code with you people.
Now to implement download file facility using PHP code follow the under given steps.
Step 1: Copy and paste under given code in your PHP file.

$filepath = 'Give full path of your file';
$filename = 'Give file name'.
header('MIME-Version: 1.0');
header('Pragma: ');
header('Cache-Control: public');
header('Content-length: '.filesize($filepath));
header('Content-type: '.mime_content_type($filepath));
header('Content-transfer-encoding: 8bit');
header('Content-disposition: attachment; filename="'.$filename.'"');
$handle = fopen($filepath, 'rb');

if ($handle)
	while (!feof($handle)) {
		print fread($handle, 8192);

Step 2: On first line replace the ‘Give full path of your file’ with full path of your file which you want to download.
Step 3: On second line replace the ‘Give file name’ with file name of your file which you want to download.
Step 4: Save the file and execute it.
Hope this will help you.


Speak Your Mind

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: