2012-12-16 55 views
1

我在我的網站上有一個php消息系統。通過它,用戶可以相互發送和接收消息,但最近我一直在試圖尋找一種包含圖像附件的方式,因此用戶可以發送帶有消息的照片。將圖像附加到php消息中?

消息存儲在ptb_messages中,並且消息部分(主體和主體)工作正常,但我在表中創建了一個名爲'image'的列,這是一個BLOB類型和一個'name'列來存儲圖像名稱。但我對PHP和MySQL不熟悉,無論我嘗試什麼,我似乎都無法將圖像存儲在數據庫中。

任何人都可以幫助我,讓我知道我要去哪裏錯了嗎?

<?php ob_start(); ?> 

<?php 

// CONNECT TO THE DATABASE 
    require('includes/_config/connection.php'); 
// LOAD FUNCTIONS 
    require('includes/functions.php'); 
// GET IP ADDRESS 
    $ip_address = $_SERVER['REMOTE_ADDR']; 

?> 


    <?php require_once("includes/sessionframe.php"); ?> 


<?php 
    confirm_logged_in(); 
    if (isset ($_GET['to'])) { 
     $user_to_id = $_GET['to']; 
    } 
?> 
<?php 
//We check if the form has been sent 
if(isset($_POST['subject'], $_POST['message_content'])) 
{ 
    $subject = $_POST['subject']; 
    $content = $_POST['message_content']; 
    $image = $POST ['image']; 

     //We remove slashes depending on the configuration 
     if(get_magic_quotes_gpc()) 
     { 
       $subject = stripslashes($subject); 
       $content = stripslashes($content); 
     $image = stripslashes($image);  
     } 

     //We check if all the fields are filled 
     if($_POST['subject']!='' and $_POST['message_content']!='') 
     { 
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content, image) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."', '".$image."');"; 
      mysql_query($sql, $connection); 

      echo "<div class=\"infobox2\">The message has successfully been sent.</div>"; 
     } 
} 
if(!isset($_POST['subject'], $_POST['message_content'])) 

if (empty($_POST['subject'])){ 
    $errors[] = 'The subject cannot be empty.'; 
    if (empty($_POST['body'])){ 
     $errors[] = 'The body cannot be empty.'; 
    } 
} 

{ 
?> 

<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post"> 
    <div class="subject"> 
    <input name="subject" type="text" id="subject" placeholder="Subject"> 
    <input type="file" name="image" id="image"> 
    <textarea name="message_content" id="message_content" cols="50" placeholder="Message" rows="8" style="resize:none; height: 100px;"></textarea> 
    <input type="image" src="assets/img/icons/loginarrow1.png" name="send_button" id="send_button" value="Send"> 
</form> 

<?php } ?> 

<?php ob_end_flush() ?> 
+0

您的代碼似乎易受[SQL注入](https://www.owasp.org/index.php/SQL_Injection)。你應該閱讀[如何防止SQL注入?](http://stackoverflow.com/q/60174/53114) – Gumbo

回答

0

我的建議是將圖像的URL存儲在數據庫中,而不是圖像文件本身。將圖像存儲在服務器文件系統中。原因在於備份和性能的概念,移動龐大的blob列並不是重複多次的好事情。此外,如果有人在沒有LIMIT子句的情況下編寫SELECT *,您將得到一個傳輸所有圖像的表掃描。這就是說,如果你堅持要在數據庫表中存儲圖像,你可能想使用base64_encode()來使圖像文件安全地進行二進制傳輸。在將圖像發送到瀏覽器之前,您會調用相應的解碼功能。

http://php.net/manual/en/function.base64-encode.php

HTH,〜雷