2016-05-16 47 views
0

我有這樣的XSS保護防止陣列從XSS

HTML //

<input class="form-control" type="text" name="pc_accesoires[]"> 

/// PHP

$pc_acc = $_POST["pc_accesoires"]; 
$accesoires = array(); 
    foreach($pc_acc as $key => $value){ 
    $accesoires[] = $value; 
} 

後,我有準備的SQL插入$ accesoires到表中,一切工作正常,沒有SQL注入,但此代碼容易受到XSS攻擊

如何保護此變量?我有嘗試ヶ輛& htmlspecialchar BU我receved錯誤是CAU的ヶ輛& & htmlspecialchar accepte一個字符串,但不是數組

回答

0

使用功能遍歷對象,檢查它是否是一個數組或沒有,並相應地消毒。這樣的東西應該工作:

function htmlspecialchars_obj(&$variable) 
{ 
    foreach ($variable as &$value) 
    { 
     // Check if item is an array or object, if so call this function recursively. 
     if (is_array($value) || is_object($value)) 
     { 
      htmlspecialchars_obj($value); 
     } 
     else 
     { 
      // Otherwise, sanitize this item and continue iteration. 
      $value = htmlspecialchars($value); 
     } 
    } 
} 

注意:這通過引用並修改您給它的參數,而不是返回編輯的副本。

下面是如何使用功能的例子:使用你提供的代碼示例

// Initialise an array/object (whatever needs to be protected). 

$myVariable = array(); 
$myVariable['xss'] = "<script>alert('xss attack');</script>"; 
$myVariable['noxss'] = "Just a plain string."; 

// Use the function: 

htmlspecialchars_obj($myVariable); 

// Now $myVariable is safe to print: 

foreach($myVariable as $key => $value){ 
    print($value); 
} 

這裏:

$pc_acc = $_POST["pc_accesoires"]; 

    htmlspecialchars_obj($pc_acc); 

    $SQLInsertReq = "INSERT INTO maintenance (pc_accesoires) VALUES (?)"; 

    $InsertRerSTMT = $connect->stmt_init(); 

    if(!$InsertRerSTMT->prepare($SQLInsertReq)){ 

     $ro = $InsertRerSTMT->error; 

     echo $ro; 

     exit(); 
    } 
    else { 

     $accesoires = mysqli_real_escape_string($connect, $accesoires); 

     $accesoires = implode(',', $accesoires) 

     $InsertRerSTMT->bind_param('s', $accesoires); 

     $InsertRerSTMT->execute(); 
    } 


    function htmlspecialchars_obj(&$variable) 
    { 
     foreach ($variable as &$value) 
     { 
      // Check if item is an array or object, if so call this function recursively. 
      if (is_array($value) || is_object($value)) 
      { 
       htmlspecialchars_obj($value); 
      } 
      else 
      { 
       // Otherwise, sanitize this item and continue iteration. 
       $value = htmlspecialchars($value); 
      } 
     } 
    } 
+0

只是這樣?哦,我的上帝 !!!我很努力:D thx很多:p –

+0

沒問題 - 請標記爲已接受的答案,如果它符合您的需求。請也刪除你的其他答案 - 這種事情會激怒管轄這個網站的權力:) – Alfie

+0

抱歉不工作:/動態添加的字段不要插入到mysql表 –

0

精細,我有保護我的字段直接療法

$pc_acc = $_POST["pc_accesoires"]; 

    $accesoires = array(); 
    foreach($pc_acc as $key => $value){ 
     $accesoires[] = htmlspecialchars($value); 
    } 

太簡單了!!!!!!!