Search code examples
phpimplode

PHP Warning: Array to string conversion


I have this code in my file:

if (is_array($_REQUEST))
   $cepl=implode(' ', $_REQUEST);

every couple of days I get this warning in php log: PHP Warning: Array to string conversion in /file.php on line 76

line 76 is: $cepl=implode(' ', $_REQUEST);

I can't find out what is causing this warning?!


Solution

  • The definition of the implode function is very roughly equivalent to this (this is just an illustration, not tested code):

    function not_really_implode($glue, $pieces) {
       $result = '';
       $first = true;
       foreach ( $pieces as $piece ) {
          if ( ! $first ) {
              $result .= $glue;
          }
          $pieceAsString = (string)$piece;
          $result .= $pieceAsString;
          $first = false;
       }
       return $result;
    }
    

    The key point is the line $pieceAsString = (string)$piece; - in order to combine the elements of the array, implode has to convert each of them in turn to strings.

    Now consider what happens if $pieces looks like this:

    $pieces = [
       'one',
       ['two-a', 'two-b'],
       'three',
    ];
    

    At some point in our loop, we're going to have $piece = ['two-a', 'two-b'], and try to convert it to a string - whoops!

    So, the warning comes about because inside your $_REQUEST array, there are other arrays. There's a couple of ways this can happen:

    1. $_REQUEST can be written to directly. For instance, someone can write $_REQUEST['example'] = ['a', 'b'];
    2. PHP recognises certain notations in input to mean arrays. For instance, someone can visit the url /your-page.php?example[]=a&example[]=b and $_REQUEST will automatically be populated with ['a', 'b'].

    This leads to a very important reminder: Never trust user input! Making any assumptions about what's in $_REQUEST is very dangerous, because that input is under the user's control, and the user might not be your friend.