Storing Files
The next step is to create a PHP script that lets users uploadfiles and store them in the database. You can hold off copying the code in
the next two sections—I'll present it all as a complete script at the
end of the chapter. Here's the code for the form—there should be no
surprises here:
<form action="<?=$_SERVER['PHP_SELF']?>?action=ulfile"
method="post" enctype="multipart/form-data">
<p>Upload File:<br />
<input type="file" name="uploadfile" /></p>
<p>File Description:<br />
<input type="text" name="desc" maxlength="255" /></p>
<p><input type="submit" name="go" value="Upload" /></p>
</form>
As you should already know from our work in "Advanced PHP", this form will create a temporary file on the server and
store the file name of that temp file in $_files['uploadfile']['tmp_name']. It also creates $_files['uploadfile']['name'] (the
original name of the file), $_files['uploadfile']['size'] (the
file size in bytes), and $_files['uploadfile']['type'] (the
MIME type of the file).Inserting the file into the database is a relatively straightforward
process: open the temporary file, read the data it contains into a PHP variable,
and then use that variable in a standard MySQL INSERT query.
Again, we make use of is_uploaded_file to make sure the file name we use does, in fact, correspond to
an uploaded file before we do any of this. Here's the code:
// Bail out if the file isn't really an upload.
if (!is_uploaded_file($_files['uploadfile']['tmp_name']))
die("$uploadfile is not an uploaded file!");
$uploadfile = $_files['uploadfile']['tmp_name'];
$uploadname = $_files['uploadfile']['name'];
$uploadtype = $_files['uploadfile']['type'];
$uploaddesc = $_POST['desc'];
// Open file for binary reading ('rb')
$tempfile = fopen($uploadfile,'rb');
// Read the entire file into memory using PHP's
// filesize function to get the file size.
$filedata = fread($tempfile,filesize($uploadfile));
// Prepare for database insert by adding backslashes
// before special characters.
$filedata = addslashes($filedata);
// Create the SQL query.
$sql = "INSERT INTO filestore SET
FileName = '$uploadname',
MimeType = '$uploadtype',
Description = '$uploaddesc',
FileData = '$filedata'";
// Perform the insert.
$ok = @mysql_query($sql);
if (!$ok) die("Database error storing file: " .
mysql_error());