note 35583 added to features.file-upload

From: Date: Sat, 06 Sep 2003 18:02:51 +0000
Subject: note 35583 added to features.file-upload
Groups: php.notes 
Request: Send a blank email to php-notes+get-55556@lists.php.net to get a copy of this message
Re: Handling uploads and downloads of large files and storing in MySQL. Use two tables to store data about the file and the file data itself. ***Important: to preserve the integrity of the data use base64_encode() NOT addslashes(). <?php // Max packet size define("MAX_SQL",50000); $filehandle = fopen($tmp, "rb") or die( "Can't open file!" ); $query= "INSERT INTO files (name, type, size) VALUES(". $DB->quote($name).", ". $DB->quote($type).", ". $DB->quote($size). ")"; // Execute Query $result = $DB->query($query); $file_id = mysql_insert_id(); // Copy the binary file data to the filedata table in sequential rows each containing MAX_SQL bytes // Your table should have an index set to auto_increment // Store the file_id to identify the data fragments while (!feof ($filehandle)) { $data = base64_encode(fread($filehandle,MAX_SQL)); $query = "INSERT INTO filedata (file_id, data) VALUES($file_id,\"".$data."\")"; $result = $DB->query($query); } fclose ($filehandle); ?> Decode the data fragments and recombine them: <?php $file_id =$_GET ['file_id']; $query ="select file_id, name, type, size from files where file_id='$file_id'"; $result = $DB->query($query); $row= mysql_fetch_array ($result); $type = $row ["type"]; $name = $row ["name"]; $size = $row ["size"]; $file_id = $row ["file_id"]; // get the file data $query = "select id, data from filedata where file_id='$file_id' ORDER by id"; $result = $DB->query($query); // decode the fragments and recombine the file $data = ""; while ($row = mysql_fetch_array($result)) { $data .= base64_decode($row ["data"]); } // output the file header ("Content-type: $type"); header ("Content-length: $size"); header ("Content-Disposition: attachment; filename=$name"); header ("Content-Description: PHP Generated Data"); echo $data; ?> ---- Manual Page -- http://www.php.net/manual/en/features.file-upload.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35583 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35583&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35583&report=yes

« previous php.notes (#55556) next »