2016-08-20 35 views
-2

我對HTML form如何使用字符串函數來清理數組變量

if(isset($_POST['job_title'])){ 
    foreach($_POST['job_title'] as $selected) { 
    $job_title[] = $selected ; 
    } 
    $job_title = json_encode($job_title); 
    $job_title = clean_string($job_title); 
} 

這個PHP代碼和這是它的SQL清除輸入所以這個時候

function clean_string($string){ 
    global $connection; 
    $string = trim($string); 
    $string = stripslashes($string); 
    $string = htmlspecialchars($string); 
    $string = htmlentities($string); 
    $string = mysqli_real_escape_string($connection,$string); 
    return $string; 
} 

clean_string功能碼代碼執行它會導致錯誤,如( 期望參數1爲字符串,數組爲

如何解決這個問題? 在此先感謝

+0

的問題是,什麼是你想停止與此消毒?你爲什麼使用'htmlspecialchars' [***和***](http://stackoverflow.com/questions/46483/htmlentities-vs-htmlspecialchars)'htmlentities'?通常全球清潔功能是適合的。 – Script47

+0

你的POST數據包含什麼內容?嘗試print_r($ _ POST) –

+0

這個變量將被插入到數據庫,所以我試圖淨化特殊字符以獲得更高的安全性! @ Script47 –

回答

0

山姆大叔可能可能認爲這是你最有可能的意圖做:

<?php 

    if(isset($_POST['job_title'])){ 
     foreach($_POST['job_title'] as $selected) { 
      $job_title[] = clean_string($selected); 
     } 
     $job_title = json_encode($job_title); 
    } 


    function clean_string($string){ 
     global $connection; 
     $string = trim($string); 
     $string = stripslashes($string); 
     $string = htmlspecialchars($string); 
     $string = htmlentities($string); 
     $string = mysqli_real_escape_string($connection,$string); 
     return $string; 
    } 

替代二:使用array_map()

<?php 
    if(isset($_POST['job_title'])){ 
     foreach($_POST['job_title'] as $selected) { 
      $job_title[] = $selected; 
     } 
     $job_title = json_encode(array_map("clean_string", $job_title)); 
    } 


    function clean_string($string){ 
     global $connection; 
     $string = trim($string); 
     $string = stripslashes($string); 
     $string = htmlspecialchars($string); 
     $string = htmlentities($string); 
     $string = mysqli_real_escape_string($connection,$string); 
     return $string; 
    } 
+0

是代碼是這樣之前的結果,但我認爲其最好把它放在使用'json_encode'之後!那麼在'json_encode'之前使用它就足夠了?@Poiz –

+0

@MustafaAlsuhaibi絕對......如果你需要在一個Array上使用它,你可以按照使用array_map() – Poiz

+0

的更新後的帖子謝謝它的工作:) –

0

從您發佈的內容看,它看起來像自定義功能clean_string($ string)接受一個字符串參數並返回一個字符串。

而你有一個陣列$ job_title需要消毒。

你面對是你在這一行傳遞一個JSON到clean_string($字符串)問題:

$job_title = json_encode($job_title); 
    $job_title = clean_string($job_title); // JSON object is passed. 

所以,你只需要通過數組$ JOB_TITLE遍歷每個元素並不斷將每個值傳遞給clean_string()。這可以使用array_map()來實現。

if (isset($_POST['job_title'])) { 
    foreach ($_POST['job_title'] as $selected) { 
     $job_title[] = $selected ; 
    } 
    $job_title = array_map("clean_string", $job_title); // Modify this line 
    $job_title = json_encode($job_title); // Add it here if you need to json encode the sanitized input 
} 
+0

你刪除了'json_encode',我更需要它,因爲' $ POST ['job_title']'包含我需要'json_encode'和'json_decode'的多個值 –

+0

在這種情況下,您可以在應用clean_string函數後應用json_encode。 –

+0

謝謝你工作:) –

相關問題