Blobbing Data With PHP and MySQL - The downloadfile.php script
(Page 6 of 7 )
As mentioned on the previous page, when we click on the "Download now" link, the downloadfile.php script will be called up, passing the id of the blob requested as the blobId query string value. Create a new file named downloadfile.php and enter the following code into it:
<?php
global $blobId;
if(!is_numeric($blobId))
die("Invalid blobId specified");
// Database connection variables
$dbServer = "localhost";
$dbDatabase = "myFiles";
$dbUser = "admin";
$dbPass = "password";
$sConn = mysql_connect($dbServer, $dbUser, $dbPass)
or die("Couldn't connect to database server");
$dConn = mysql_select_db($dbDatabase, $sConn)
or die("Couldn't connect to database $dbDatabase");
$dbQuery = "SELECT blobType, blobData ";
$dbQuery .= "FROM myBlobs ";
$dbQuery .= "WHERE blobId = $blobId";
$result = mysql_query($dbQuery) or die("Couldn't get file list");
if(mysql_num_rows($result) == 1)
{
$fileType = @mysql_result($result, 0, "blobType");
$fileContent = @mysql_result($result, 0, "blobData");
header("Content-type: $fileType");
echo $fileContent;
}
else
{
echo "Record doesn't exist.";
}
?>In the code above we use the query string variable $blobId to retrieve the blobType and blobData fields from our myBlobs database. If there was a row returned from our query, then we save its type and actual data to two variables, called $fileType and $fileContent respectively.
We use the header function to change the type of content that we are sending to the browser. The default content type is text/html, which the browser assumes is a web page. If we didn’t include a call to the header function, then when we output our binary data it will look like garbage in the browser. Lastly, we use the echo command to actually output the contents of our binary file to the browser, which handles the file as it sees fit.
Take a look at the screen shots below for how the script works with different file types:
For Images:
For HTML documents:
For MS Word documents:
Next: Conclusion >>
More MySQL Articles
More By Mitchell Harper