2016-05-16 46 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); 
    } 

太简单了!!!!!!!