2012-01-09 121 views
0

嗨我想知道如果有人可以看看我的代碼,看看有什麼錯誤,因爲我不能看到任何。發生的事情是,它不會保存我發送給mysql的電子郵件,而是我收到了一封退回的電子郵件。電子郵件不保存到mysql

當我運行PHP測試以查看它是否保存到mysql表中時,它不會。

我已經取出了連接代碼,因爲它有我的用戶名和密碼。

#!/usr/bin/php -q 
<?php 
mysql_connect("123.123.123.2", "abc_ard", "5555") or die(mysql_error()); 
mysql_select_db("55_servermail") or die(mysql_error()); 

chdir(dirname(__FILE__)); 
$fd = fopen("php://stdin", "r"); 
$email = ""; 
while (!feof($fd)) { 
    $email .= fread($fd, 1024); 
} 
fclose($fd); 

if(strlen($email)<1) { 
    die(); 
} 

// handle email 
$lines = explode("\n", $email); 

// empty vars 
$from = ""; 
$to=""; 
$subject = ""; 
$headers = ""; 
$message = ""; 
$splittingheaders = true; 

for ($i=0; $i < count($lines); $i++) { 
    if ($splittingheaders) { 
     // this is a header 
     $headers .= $lines[$i]."\n"; 
     // look out for special headers 
     if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) { 
      $subject = $matches[1]; 
     } 
     if (preg_match("/^From: (.*)/", $lines[$i], $matches)) { 
      $from = $matches[1]; 
     } 
     if (preg_match("/^To: (.*)/", $lines[$i], $matches)) { 
      $to = $matches[1]; 
     } 
    } else { 
     // not a header, but message 
     $message .= $lines[$i]."\n"; 
    } 
    if (trim($lines[$i])=="") { 
     // empty line, header section has ended 
     $splittingheaders = false; 
    } 
} 


mysql_query("INSERT INTO mail 
(`to`,`from`,`header`,`subject`,`msg`,`original`) 
VALUES 
('{$to}','{$from}', '{$headers}','{$subject}','{$message}','{$email}')") or die(mysql_error());; 


?> 
+1

你能打印出來的查詢文本,並直接將其送入mysql數據庫?你的話很不清楚。 – user482594 2012-01-09 05:33:30

+0

您可以發佈您將放在電子郵件字段中的示例值嗎? – 2012-01-09 07:24:34

回答

0

向mysql添加信息時,必須考慮mysql和PHP使用的字符並解決它們,因爲它們可能導致代碼失敗,甚至允許人們在您的網站上插入和/或執行代碼。我用最簡單的方法是讓PHP「越獄」人物,使他們能夠插入MySQL的正確:

$email = "This isn't my first time 'round here"; 

這應該罰款插入原樣,但是讓我們假設你的SQL是這樣的:

$query = "INSERT INTO table (timestamp,email) VALUES (time(),'$email')"; 

MySQL查詢中的單引號將被數據中的單引號括起來。爲了避免這種情況設置電子郵件變量進行轉義:

$email = "This isn't my first time 'round here"; 
$email = mysql_escape_string($email); 

的caviat使用這個,現在你的數據庫在數據額外的轉義字符(通常是一個反斜槓「/」),所以當你想使用這些從數據庫中,你將不得不刪除它們,PHP有隻爲這一個方便的功能:

$query = "SELECT * FROM table WHERE id='the id you want'"; 
    $result = mysql_query($query) or die(mysql_error()); 
    while ($data = mysql_fetch_array($result)) { 
     $email = stripslashes($data['email']); 
    } 

    echo "This is your email text from the database: <br>\n".$email."<br>\n"; 

希望幫助澄清一個可能的解決方案(如果這是真的,爲什麼電子郵件沒有插入數據庫如預期)。

0

那我可能在當前的代碼中看到的唯一的錯誤是輸入字符,如單引號(')請確認的可能性,如果你希望它被包含在郵件正文或其他領域確保使用反斜槓(),例如(\'),以便mysql將它分析爲一個特徵,而不是一個閉合的撇號,但確實有一個安全措施來避免sql注入。 :)

相關問題