ngplayground
ngplayground

Reputation: 21627

PHP Notice: Array to string conversion Error

Been experiencing this error for a little while and can't find any conclusive answers on fixing it. I have tried removing quotes from $key in line 59 but to no avail.

if (!get_magic_quotes_gpc()) {
    if (isset($_POST)) {
        foreach ($_POST as $key => $value) {
            $_POST['$key'] =  trim(addslashes($value));
        }
    }

    if (isset($_GET)) {
        foreach ($_GET as $key => $value) {
            $_GET[$key] = trim(addslashes($value));
        }
    }   
}

LINE 59

$_POST['$key'] =  trim(addslashes($value));

Error On Screen

Notice: Array to string conversion in C:\Inetpub\vhosts\domain.com\httpdocs\library\config.php on line 59

Upvotes: 3

Views: 54575

Answers (4)

Barmar
Barmar

Reputation: 781004

Do this:

foreach ($_POST as &$value) {
    $value = is_array($value) ?
        array_map(function($x) { return trim(addslashes($x)); } :
        trim(addslashes($value));
}

However, this could still fail if any of your parameters are multi-dimensional arrays. As mentioned in the comments, the right solution is to use prepared queries with parameters, rather than interpolating strings into SQL.

Upvotes: 0

vanurag
vanurag

Reputation: 297

I think you should use this code $_POST[$key] = $value; instead of using this $_POST['$key'] = trim(addslashes($value));

or make a check if the value is in array or not

Upvotes: 0

According to PHP.net the function addslashes() takes a String type as parameter. Check what type $value is. If it is an array itself then addslashes() may be throwing the error.

PS: You should use $_POST[$key] rather than $_POST['$key'] if you want to use the value of $key as the index of the $_POST array.

Upvotes: 0

Starx
Starx

Reputation: 78991

Check if it is array before you assign it

$_POST[$key] =  !is_array($value) ? trim(addslashes($value)) : '';
   //  ^   Remove the quotes here                          //  ^ Do something 
                                                           //  Instead of 
                                                           //  Using empty

Upvotes: 2

Related Questions