1. 程式人生 > >php將圖片以二進位制儲存到mysql資料庫並顯示

php將圖片以二進位制儲存到mysql資料庫並顯示

<?php
include('./conn.php');
if ($_POST['submit']) {
    
if ($_FILES['image']['size']) {
        $names = 
$_FILES['image']['name'];
        $arr   = explode(
'.', $names);
        $name  = $arr[
0]; //圖片名稱
        $date  = date('Y-m-d H:i:s'); //上傳日期
        $fp    = fopen($_FILES['image']['tmp_name'], 'rb');
        $type  = 
$_FILES['image']['type'];
        
if (!$fp) {
            showInfo(
'讀取圖片失敗!');
        } 
else {
            $image = addslashes(fread($fp, filesize(
$_FILES['image']['tmp_name'])));
            
if ($image) {
                $q      = 
"insert into image (name, pic, type, date) values ('$name','$image','$type','$date')"
;
                $result = mysql_query($q);
                
if ($result) {
                    showInfo(
'上傳成功!');
                } 
else {
                    showInfo(
'上傳失敗!');
                }
                
            } 
else {
                showInfo(
'請選擇要上傳的檔案!');
            }
        }
        
    } 
else {
        showInfo(
'請選擇要上傳的檔案!');
    }
}

function showInfo($info)
{
    
echo"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
    
echo"<meta http-equiv='refresh' content='1;url=index.php'>";
    
echo"</head>";
    
echo"<body>" . $info . "……</body>";
    
echo"</html>";
}
?>