PHP warning: cannot convert array to string
P粉101708623
2023-08-15 22:27:37
<p>I have this code in my file: </p>
<pre class="brush:php;toolbar:false;">if (is_array($_REQUEST))
$cepl=implode(' ', $_REQUEST);</pre>
<p>Every few days I get the following warning in the php log:
PHP warning: Converting array to string </p> in /file.php, line 76
<p>Line 76 is: $cepl=implode(' ', $_REQUEST);</p>
<p>I can't figure out what causes this warning? ! </p>
The definition of function
The key point is this line of code:implode
is very roughly equivalent to the following code (this is just an example, not tested):$pieceAsString = (string)$piece;
Now consider if- In order to combine the elements of the array,
implodemust
each element one by oneConvert to string.$pieces
At some point in our loop we will havelooked like this:
$piece = ['two-a', 'two-b']
So the reason the warning appears is because withinand try to convert it to a string - oops!
your $_REQUEST
array, there are other arrays. Several ways this could happen:
can be written directly. For example, someone could write
$_REQUEST['example'] = ['a', 'b'];, and
$_REQUESTwould be automatically populated as
['a', 'b '].
Never trust user input! It is very dangerous to make any
assumptions about the content in
$_REQUEST, because the input is under the control of the user, and the user may not be yours friend.