note 35583 deleted from features.file-upload by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 17:05:38 +0000 |
| Subject: | note 35583 deleted from features.file-upload by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176148@lists.php.net to get a copy of this message | ||
Note Submitter: therebechips
----
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;
?>