correct way to upload image to database

╄→尐↘猪︶ㄣ 提交于 2019-11-29 13:16:25

Using addslashes is extremely incorrect. Depending on whether your column is a TEXT field or a BLOB field, you should use Base64 or mysql_real_escape_string.

Using Base64 isn't that hard; you may as well use that way. Just replace addslashes with base64_encode and echo the image with base64_decode.

There's a bit easier way to write the whole thing, for that matter:

// begin upload
if ($imgsize > 0)
{
  $content = file_get_content($tmpname);
  $content = base64_encode($content);
}

And then to output you really only need to do

header("Content-type: ".$imgtype);
echo base64_decode($img);

If the column is a BLOB, however, you can directly use mysql_real_escape_string:

// begin upload
if ($imgsize > 0)
{
  $content = file_get_content($tmpname);
  $content = mysql_real_escape_string($content);
}

And then:

header("Content-type: ".$imgtype);
echo $img;

Although judging from your current symptoms, I'm guessing you also have a bug relating to how your image is being stored and recalled from the database, and I'd need to see that part of the code where you make the queries to insert and read from the database before I could help you fix that part.


Your current code seems mostly fine. A few issues:

print base64_decode($row['img']);

print $row['img'];

You probably meant to get rid of the second row. Also, you should use echo instead of print; everyone uses it, it can be slighty faster sometimes, and print doesn't really have any benefit other than returning a value:

echo base64_decode($row['img']);

$security->secure() appears to be some sort of sanitization function. Just use mysql_real_escape_string() - that's the one you're supposed to use. Except $imgsize; you might want to use intval() on that one since you know it's supposed to be an integer.

Also here:

$query = mysql_query("select * from $tbl where id = '$id'") or die(mysql_error());

You name the table tbl_schoolgallery a few rows above that. I assume $tbl == 'tbl_schoolgallery', but for consistency, you should either use $tbl in both places or tbl_schoolgallery in both places.

Also, replace that while with an if - your code would cause trouble if it ever loops more than once, anyway.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!