Archive for November, 2009
PHP downloadable file
Written by Codes Tips on November 18, 2009 – 1:40 pm -Text downloadable file
Last days I needed to create a file which had to be downloaded by many users. The file had to be in plain text and contents from file come from database. Because I didn’t had a separate folder for each user I couldn’t write the information to a file to the server and put a link in order the user to download it. I thought a little bit how to handle it and found a very simple solution to to make a file downloadable to users. I even try to other popular formats like .doc, .xls,.csv,.dat and it works really nice. Extension that I tested it and didn’t worked are .xlsx and .pdf.
In order to make a file downloadable you should modify the header of the page to make Content-type: application/octet-stream and Content-Disposition: attachment; filename=\”downloadableFile.extension\” in order to inform the browser that there is an attachment binary file. The file will open in a window to inform the user it to open it with a default application or save it to disk.
Code for downloadable file:
<? header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"downloadablefile.txt\""); echo 'Contents of plain text downloadable file'; ?>
CSV downloadable file
The real magic comes when you wanna make csv file downloadable. You can read data from a mysql table and write the contents to a csv file. You should only read contents from a table and using echo output to the file.
<? header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"downloadablefile.csv\""); $connect = mysql_connect($server, $user, $password) or die ("Database CONNECT Error"); $resultcsv = mysql_db_query($database, "select * from $csvTable"); while ($query = mysql_fetch_array($resultcsv)) { echo $query["Name"].",".$query["City"]."\n"; } mysql_close($connect); ?>
Excel downloadable file
Code for generating a excel downloadble file:
<? header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"downloadableFile.xls\""); $connect = mysql_connect($server, $user, $password) or die ("Database CONNECT Error"); $resultxls = mysql_db_query($database, "select * from $xlsTable"); while ($query = mysql_fetch_array($resultxls)) { echo $query["Name"]."\t".$query["City"]."\n"; } mysql_close($connect); ?>
You can look through records from database and output as I did for csv
Doc downloadable file
You can even make a downloadable .doc files by changing the file extension to doc.
<? header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"downloadablefile.doc\""); echo 'Contents of Word Document.'; ?>
Tags: PHP, PHP/MYSQL
Posted in PHP/MYSQL | No Comments »


















