This article will share with you two small details that are easily overlooked when using PHP for development, namely, empty and in_array. if you need them, you can refer to them. Some technical details may be forgotten during development. These details may cause serious consequences, such as website injection and website crash. Now Let's summarize some of the "traps" in PHP ".
Trap 1: empty ()
<? Php // the following code will directly cause PHP parsing errors $ arr1 = [1, 2, 3]; $ arr2 = [3, 4]; if (empty (array_diff ($ arr1, $ arr2) {// resolution error echo 'empty';} else {echo 'not empty ';}
The latest manual on the official website has special instructions on this:
Note:
Before PHP 5.5, empty () only supports variables; anything else will cause a parsing error.
In other words, the following code does not take effect: empty (trim ($ name )). As an alternative, trim ($ name) = false should be used.
The last time I encountered this error was when I used Phalcon for development, the server always reported the 503 error. at the beginning, I thought it was inexplicable. by troubleshooting it row by row, empty error occurs. Of course, empty has supported this method since PHP 5.5.
Trap 2: in_array ()
<? Php // Determine whether the user ID submitted BY the user exists in the array // $ post_dirty_id = '000000'; $ post_dirty_id = '2017 order by #1 '; $ safe_arr = [987 => 'xiaoming ', 1092 => 'Tom', 1256 => 'orelevation ']; if (in_array ($ post_dirty_id, array_keys ($ safe_arr ))) {echo 'find me';} else {echo 'do not find me';} // output result: find me. this result is obviously incorrect.
I found this problem because the website was injected with SQL statements. Fortunately, what I found during the test did not cause serious consequences.
For the use of in_array () functions, there are other points worth our attention. in the PHP manual, there are a large number of examples provided by netizens to illustrate the "weird" behavior of the function, such:
<?php $a = ['a', 32, true, 'x' => 'y']; var_dump(in_array(25, $a)); // true, one would expect false var_dump(in_array('ggg', $a)); // true, one would expect false var_dump(in_array(0, $a)); // true var_dump(in_array(null, $a)); // false
For the sake of security, we recommend that you use the following method for determination:
<? Php // Determine whether the ID submitted BY the user exists in the array // $ post_dirty_id = '000000'; $ post_dirty_id = '2017 order by #1 '; $ safe_arr = [987 => 'xiaoming ', 1092 => 'Tom', 1256 => 'orelevation ']; if (isset ($ safe_arr [$ post_dirty_id]) {echo 'find me';} else {echo 'do not find me';} // output result: do not find me, which is correct.