2014-02-26 33 views
1

我剛剛開始嘗試學習php和mysql,所以我的知識水平對於兩者都是相當原始的。有沒有辦法添加stripslashes和mysql轉義字符串來清理數據?

我不太確定stripslashes方法,所以我想知道下面的代碼是否足夠安全,以防止SQL注入或其他惡意攻擊我的數據庫?除了stripslashes方法之外,數據庫是否會受益於添加mysql_real_escape_string?

$first = Trim(stripslashes($_POST['First'])); 
$last = Trim(stripslashes($_POST['Last'])); 
$city = Trim(stripslashes($_POST['City'])); 
$state = Trim(stripslashes($_POST['State'])); 
$country = Trim(stripslashes($_POST['Country'])); 
$email = Trim(stripslashes($_POST['Email'])); 
$tempt = $_POST['tempt']; 
$tempt2 = $_POST['tempt2']; 


if ($tempt == 'http://' && empty($tempt2)) { 

    $error_message = ''; 
    $reg_exp = "/^[a-zA-Z0-9._%+-][email protected][a-zA-Z0-9­-]+\.[a-zA-Z.]{2,5}$/"; 

    if(!preg_match($reg_exp, $email)) { 

     $error_message .= "<p>A valid email address is required.</p>"; 
    } 
    if (empty($first)) { 
     $error_message .= "<p>Please provide your first name.</p>"; 
    } 
    if (empty($last)) { 
     $error_message .= "<p>Please provide your last name.</p>"; 
    } 

    if (!empty($error_message)) { 

     $return['error'] = true; 
     $return['msg'] = "<p>The request was successful, but the form was not filled out correctly.</p>".$error_message; 
     echo json_encode($return); 
     exit(); 

    } else { 

     $return['error'] = false; 
     $return['msg'] = "<p style='top:9px; color:#ff6000; left:63px; text-align:left; font-size:1.50em;'>".$first .", <p style='top:0px; width:100%; left:63px; text-align:left; line-height:1.1em;'>your subscription request has been processed.</p>"; 
     echo json_encode($return); 
    } 

} else { 

     $return['error'] = true; 
     $return['msg'] = "<p>There was a problem while sending this form. Try it again.</p>"; 
     echo json_encode($return); 
} 
+4

您應該使用準備好的語句來避免pdo或mysqli的安全問題。 Mysql_ *函數已棄用 – Fabio

+1

不是,此外,是的。數據庫有他們不喜歡的字符,只有數據庫驅動程序的函數知道哪些字符。它不僅僅是逃避所有'''。法比奧說的。 – Rudie

+0

如果您在HTML中首先打印$,則應該使用html進行編碼。將其轉義爲數據庫,而不是html。 Html將其編碼爲html,而不是數據庫。雙從不好。 – Rudie

回答

1

我創建了一個函數。只要傳遞要消毒的價值即可。

function clean($data) { 
    $data = trim($data); 
    $magic_quotes_active = get_magic_quotes_gpc(); 
    $new_enougth_php = function_exists("mysql_real_escape_string"); 
    if ($new_enougth_php) { 
     if ($magic_quotes_active) { 
      $value = stripslashes($data); 
     } 
     $value = mysql_real_escape_string($data); 
    } else { 
     if (!$magic_quotes_active) { 
      $value = addcslashes($data); 
     } 
    } 
    return $value; 
} 
0

我沒有看到你的代碼中的任何數據庫查詢,但放眼評論有關準備語句/沒有mysql_建議*功能等。

你只需要stripslashes如果magic_quotes_gpc啓用在php.ini中,請嘗試:

if(get_magic_quotes_gpc()) { 
    $_POST = array_map('stripslashes', $_POST); 
} 
相關問題