Simple PHP Image Upload
I consider myself a fairly descent programmer, not great by any means, but ok; anyway I spent the last three days struggling over a form that would upload a picture to mysql. It shouldn’t be a problem because it’s pretty basic, but I couldn’t get it to work. Why?!!! Gawd, it was frustrating the hell out of me. The form kept passing an empty array…over and over and over I worked with it making the simplest of script and still nothing. Then this morning it dawned on me. I had an epiphany…the harps and trumpets played in tandem at the back of my frustrated mind. *sigh* I was using $_POST and not $_FILES.
Anyhow, here is some simple code for anyone that wants it.
form.php
<?php
if (!empty($_FILES['imgfile'])){
echo '<form action="form.php" method="post" enctype="multipart/form-data" >
<input type="file" name="imgfile">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
</form>';
}else{
$image = $_FILES['imgfile'];
//make sure this folder is writeable 666
$path = '/home/user/public_html/images/';
copy($image['tmp_name'], $path.$image['name']);
}
?>
This simple script uploads a file, and then copies it from the temporary php upload directory to your permanent directory with its original name.
If you wanted to insert the object into a mysql database, then, to save space one would encode it - basically turn it into a text file - and insert the image into a field with type longtext. The code would look something like this. Again, this is pretty simple code and no error capture. Code takes off from above.
copy($image['tmp_name'], $path.$image['name']);
//open file for reading
$fp = fopen($path.$image['name'], "r");
//measure the file contents
$contents = fread($fp, filesize($path.$image['name']));
//close the file
fclose($fp);
//encode the file to save space in the db
$encoded = chunk_split(base64_encode($contents));
//my assumption is that you already have a db setup with a longtext field.
mysql_query("INSERT INTO images (ID, IMAGE) VALUES (" . $id . ",'" . $encoded . "')");
//since it's inserted into mysql, you can delete the existing file
unlink($path.$image['name']);
So now, how do we view the file? Good question and I don’t know….
Nah, here you go
image.php
<?php
//My assumption is that you already have connected to the database somewhere
//and the db has an id field
$result=mysql_query("SELECT * FROM images WHERE ID='".$_GET['img']."'");
//fetch data from database
$data=mysql_fetch_array($result);
$encoded=$data['data'];
//close connection
mysql_close($connection);
//decode and echo the image data
echo base64_decode($encoded);
?>
This is a simple usage of it.
<img src=”image.php?img=32″ border=”0″>