简体   繁体   中英

INSERT IMAGE INTO DATABASE and enctype=“multipart/form-data”

I'm trying to insert an image into my database. I've read a few posts and I'm clearly doing this wrong. I know that the column datatype needs to be a blob for the image. This I have done.

My form looks like this:

<form id="Dev_test" name="Dev_test" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP']);?>" enctype="multipart/form-data">
<input type="file" name="call_file" id="call_file">
<input type="submit" name="submit" id="submit" value="SUBMIT">
</form>

This is where I've seen multiple variations of how to do this, and I even came across a post that said this might not be possible.

$query = "INSERT INTO `******`.`******` (img) values ('{$_POST['file']}')"

I know the above isn't right.

So my question(s) is/are the following, is there a reason why $_POST['file'] isn't posting, and is there a better method to insert the image into my database? As an fyi, I'm aware that inserting an image directly into the database is not the most efficient method and that there are other methods by referencing file paths.

What you want to use is php's $_FILES superglobal instead.

$content = file_get_contents($_FILES['call_file']['tmp_name']);

You may want to do virus checking on $content or the like.

I would also suggest that you store the file on the system rather than as a blob in the database and store the path to the file instead.

To store image file in a DB (which is generally a bad idea because filesystem is an db designed specially for effective storing of files) you need to read the contents of the uploaded file and then put it into the query.

In php you should use $_FILES global array to get information about uploaded files, use is_uploaded_file() to check if everything is ok with uploaded file, then you have to read the contents of the uploaded file with standard file access functions and then you MUST escape the contents of the file when inserting it to database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM