HomePHP Secure Encrypting and Decrypting for Your PHP Website
Secure Encrypting and Decrypting for Your PHP Website
In this conclusion to a three-part series on secure PHP programming, you'll learn how to validate inputs, handle hashing, use the MCrypt package, and more. This article is excerpted from chapter 21 of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).
The htmlentities() function converts certain characters that have special meaning in an HTML context to strings that a browser can render as provided rather than execute them as HTML. Its prototype follows:
string htmlentities(string input [, int quote_style [, string charset]])
Five characters in particular are considered special by this function:
& will be translated to &
" will be translated to " (when quote_style is set to ENT_NOQUOTES )
> will be translated to >
< will be translated to <
' will be translated to ' (when quote_style is set to ENT_QUOTES )
Returning to the cross-site scripting example, if the user’s input is passed through htmlspecialchars() rather than embedded into the page and executed as JavaScript, the input would instead be displayed exactly as it is input because it would be translated like so:
Sometimes it is best to completely strip user input of all HTML input, regardless of intent. For instance, HTML-based input can be particularly problematic when the information is displayed back to the browser, as is the case of a message board. The introduction of HTML tags into a message board could alter the display of the page, causing it to be displayed incorrectly or not at all. This problem can be eliminated by passing the user input through strip_tags() , which removes all HTML tags from a string. Its prototype follows:
The input parameter str is the string that will be examined for tags, while the optional input parameter allowed_tags specifies any tags that you would like to be allowed in the string. For example, italic tags ( <i></i> ) might be allowable, but table tags such as <td></td> could potentially wreak havoc on a page. An example follows:
<?php $input = "I <td>really</td> love <i>PHP</i>!"; $input = strip_tags($input,"<i></i>"); // $input now equals "I really love <i>PHP</i>!" ?>