Mustafa Alsuhaibi Mustafa Alsuhaibi - 1 year ago 67
PHP Question

How to use string functions to clean array variables

I have this php code for html


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

and the this is what
function code which cleans input for 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;

So when this code execute it cause an error like(
expects parameter 1 to be string, array given)

How to solve this problem ?
Thanks in advance

Answer Source

From what you've posted, it looks like the custom function clean_string($string) accepts a string parameter and returns a string.

And you have an array $job_title which needs to be sanitized.

The problem you're facing is you're passing a JSON to clean_string($string) in this line:

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

So, you simply need to traverse each element through the array $job_title and keep passing each value to clean_string(). This can be achieved using 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