Image storage using databases in PHP

To make an image database script we will first create a form that will allow the user to select a file from their computer.

<form action="#" method="post" enctype="multipart/form-data" name="form" id="form">
   Image Upload:<br />
   <input type="file" name="image" id="image" />
   <input type="submit" name="submit" id="submit" value="Submit" />
</form>

This simple form has a file field and a submit button. When the user posts the form we will check the size and dimensions of the image and check that they are less than predefined values.

$files = array('image/gif','image/jpeg','image/png');
$max_size = 1000000;
$max_height = 500;
$max_width = 500;
$dir = getcwd().'/';
$filename = $dir.$_FILES['image']['name'];
list($width, $height, $type, $attrib) = getimagesize($_FILES['image']['tmp_name']);

These variables hold the maximum file size and dimension that we will upload as well as a list of image types that we will upload.

if(in_array($_FILES['image']['type'], $files) && 
   $_FILES['image']['size'] <= $max_size &&
   $width <= $max_width &&
   $height <= $max_height)

This conditional statement checks the file against the specified values.

if(is_uploaded_file($_FILES['image']['tmp_name']) && move_uploaded_file($_FILES['image']['tmp_name'], $filename))
{
   mysql_connect('localhost','username','password');
   mysql_select_db('db');
   $date = time();
   $name = ucwords(reset(explode('.', $_FILES['image']['name'])));
   if(mysql_query("INSERT INTO images (id, name, width, height, location, date) VALUES 
                 ('', '$name', '$width', '$height', '$filename', '$date')"))
      echo 'File '.$_FILES['image']['name'].' successfully uploaded.';
   else
      echo 'Database error';

We now check that the file has been uploaded and enter the image details into the database. The name of the file as well as the full file name are entered and the height and width of the image followed by the date it was entered.

   }
   else
      echo 'Cannot upload file.';
}
else
   echo 'File not allowed.';

Finally we alert the user if any of the image constraints are not met.

Downloads

Categories

Tags

Social