hello,
I am currently working on CMS and I want a way for the user to upload images to go along with their post

how would I upload the image with php and then add it into the database for later retrieval when people look at the posts?

Recommended Answers

All 4 Replies

I think you can save the image on the server drives but not on the database itself. The path of the image is the one that saves in the database.

I think you can save the image on the server drives but not on the database itself. The path of the image is the one that saves in the database.

That's one way to do it, but you can also save the actual image in the database in a BLOB (Binary Large OBject) column. You could do something like this:

Create a table in the database to store the images:

CREATE TABLE images (
  id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  mime VARCHAR(50),
  filename VARCHAR(255),
  imagedata MEDIUMBLOB
);

To add the image to the database:

$yourimage = (object)$_FILES[$your_image_input_name];
if ($yourimage->error == UPLOAD_ERR_OK)
{
  $dbinsert = new stdClass;
  $dbinsert->mime = $yourimage->type;
  $dbinsert->filename = $yourimage->name;

  // read the image file into your data object
  $dbinsert->imagedata = 
    addslashes(fread(fopen($yourimage->tmp_name, 'r'), $yourimage->size));

  // execute a sql statement inserting the values in $yourimage into the database
}
else
{
  // there was an error with the form submission
}

To later view your image, link to viewimage.php?id=THE_ID_OF_THE_IMAGE_YOU_WANT:

// file viewimage.php
$id = $_GET['id'];

// validate the id by trying to load the image from the database
// e.g. $image = your_database_query_function("SELECT * FROM images WHERE id='{$id}'");

// now that you have the image data, send it to the browser (there
// are surely better ways to do this, but this is what comes to
// mind and I've used it in the past)
header("Content-type: {$image->mime}");
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment; filename=\"{$image->filename}\"");
print(stripslashes($image->imagedata));
exit;

thanks that was helpful!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.