mysql File Upload
Original posted by: Admin on 12-04-2007
When uploading a file most people will save it do a directory somewhere on the server. This isn't always the optimal solution, if you are expecting to have 1000's of files to be uploaded you may want to save it to your database instead of directory.
The first step is to setup your database table.
CREATE TABLE `db_file` (
`img_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`img_name` VARCHAR( 250 ) NOT NULL ,
`img_type` VARCHAR( 100 ) NOT NULL ,
`img_type` LONGTEXT NOT NULL ,
`img_time` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)
Ok, now that our database table is setup lets create a simple upload script. Our HTML page will be very plain and simple.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Image Files</title>
</head>
<body>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file" />
<input type="submit" name="submit" value="Upload!" />
</form>
</body>
</html>
Now our page is ready to go, all we need is our PHP script which will upload the file. Place this script up the top of your upload page.
<?php
//Connect
$connect = mysql_connect('localhost', 'root', '');
mysql_select_db('random', $connect);
if(isset($_POST['submit'])) {
//File Type
$file_type = $_FILES['upload_file']['type']
//File Name
$file_name = basename($_FILES['upload_file']['name']);
//File Data
$file_data = chunk_split(base64_encode(file_get_contents($_FILES['upload_file']['tmp_name'])));
//Insert into database
@mysql_query('INSERT INTO `db_file` (`img_file`, `img_type`, `img_name`)
VALUES ("'.$file_data.'", "'.$file_type.'", "'.$file_data.'")');
}
?>
This will connect to your database and insert the image straight into your selected table.
Now that the image is in your database how do you get it out? Simple!
Create a file called "image.php"
<?php
//Connect to database
$connect = mysql_connect('localhost', 'root', '');
//Select Database
@mysql_select_db('random', $connect);
//Get data
$r = @mysql_fetch_assoc(@mysql_query('SELECT * FROM `db_file`
WHERE `img_id` = "'.$_GET['id'].'" LIMIT 0,1'));
//Create Header
@header('Content-Type: '.$r['img_type']);
//Print image
echo base64_decode($r['img_file']);
//Exit
exit();
?>
Now all you have to do to access your image is call "image.php?id=1" or you can use "<img src='image.php?id=1' />'
How easy is that? Now you don't have to worry about setting permissions on your folders and all those other problems like unique names and ids. It's all sorted!