PHP implements the method of uploading images and saving them to the database. Share it with everyone for your reference. The specific analysis is as follows:
PHP uploads images, generally using the move_uploaded_file method to save them on the server. But if a website has multiple servers, it needs to publish the images to all servers for normal use (except those using image servers)
If the image data is saved in the database, files can be shared among multiple servers to save space.
First of all, the image file is binary data, so the binary data needs to be saved in the mysql database.
The mysql database provides the BLOB type for storing large amounts of data. BLOB is a binary object that can accommodate data of different sizes.
There are four types of BLOB, which are the same except for the maximum amount of information stored. Different types can be used depending on your needs.
TinyBlob Maximum 255B
Blob Max 65K
MediumBlob Max 16M
LongBlob Maximum 4G
Data table photo, used to save image data, the structure is as follows:
upload_image_todb.php:
// 判断action
$action = isset($_REQUEST['action'])? $_REQUEST['action'] : '';
// 上传图片
if($action=='add'){
$image = mysql_escape_string(file_get_contents($_FILES['photo']['tmp_name']));
$type = $_FILES['photo']['type'];
$sqlstr = "insert into photo(type,binarydata) values('".$type."','".$image."')";
@mysql_query($sqlstr) or die(mysql_error());
header('location:upload_image_todb.php');
exit();
// 显示图片
}elseif($action=='show'){
$id = isset($_GET['id'])? intval($_GET['id']) : 0;
$sqlstr = "select * from photo where id=$id";
$query = mysql_query($sqlstr) or die(mysql_error());
$thread = mysql_fetch_assoc($query);
if($thread){
header('content-type:'.$thread['type']);
echo $thread['binarydata'];
exit();
}
}else{
// 显示图片列表及上传表单
?>
希望本文所述对大家的php程序设计有所帮助。