The following section of the "poor" PHP code is a simplified test question. This is like a question: how do you optimize this code?
<?
Echo ("<p> search results for query :".
$ _ Get ['query']. ". </P> ");
?>
The main problem with this Code is that it directly displays the data submitted by the user on the webpage, resulting in an XSS vulnerability. There are actually many ways to fill this vulnerability. So what code is what we want?
<?
Echo ("<p> search results for query :".
Htmlspecialchars ($ _ Get ['query']). ". </P> ");
?>
This is the minimum requirement. The XSS vulnerability is filled by the htmlspecialchars function, thus blocking invalid characters.
<?PHP
If (isset ($ _ Get ['query'])
{
Echo '<p> search results for query :',
Htmlspecialchars ($ _ Get ['query'], ent_quotes), '. </P> ';
}
?>
The person who can write such code should be the one I want to hire.
- <? Replaced with <?PHP.
- Determine whether the value of $ _ Get ['query'] is null before outputting it.
- The extra parentheses in the ECHO command are removed.
- The string is limited by single quotes, saving PHP time to search for replaceable variables from the string.
- Use commas instead of periods to save the echo time.
- Pass the ent_quotes identifier to the htmlspecialchars function to ensure that the single quotation marks are also escaped. Although this is the most important thing, it is also a good habit.
Unfortunately, few programmers can give such satisfactory answers.