Link to home
Start Free TrialLog in
Avatar of iDeej
iDeejFlag for Australia

asked on

Best PHP security technique for when working with forms.

I learning about PHP security and in the book PHP 5 advanced by Larry Ullman It says to lookout for and replace '\n' and '\r'.

Below is how I have gone about this. Is this the best way to go? Is it needed? Is there a better way.

I ask because I have a few PHP books and none of them seem to do anything like this.

Thanks,
Daniel.
// Check that the conSubject field is less than 100 characters
// Check that the conSubject field does not contain '\n' or '\r'
$pos = strpos($conSubject, '\n');
$pos = !$pos ? strpos($conSubject, '\r') : $pos; 
if (strlen($conSubject) > 100 || !($pos === false)) {
  $errors[] = 'The name field must be 100 characters or less and must consist of letters or spaces only';
}

Open in new window

SOLUTION
Avatar of Matthew Kelly
Matthew Kelly
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Form data can contain anything, so there's no single formula for validating form data. The questions to ask are:

* what values are useful to my script (for instance, no point allowing newlines in a "username" or "phone number" field);
* what am I going to do with the user-supplied data (dump it into an HTML page / store it in a MySQL database, etc).

If you're going to dump user-supplied data into an HTML page, you must use htmlspecialchars (and make sure to use the ENT_QUOTES flag) to avoid any embedded markup or scripting in the user-supplied data being treated as part of your page.

If you're going to store user-supplied data into a MySQL database, see the real_escape_string function:

http://php.net/manual/en/function.mysql-real-escape-string.php

which escapes quotes and backslashes so that user-supplied data cannot inject SQL statements into your database queries.
Avatar of iDeej

ASKER

Ok so wrapping this up, Larry in his book says to take out or replace \r and \n with emails.

Could you please tell me what problems \r and \n could cause?

And instead of the lengthy code I used above could I just use mysql_real_escape_string to render \r ineffective?

Avatar of iDeej

ASKER

Some great information by the way. Very much appreciated!
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of iDeej

ASKER

Thank you kindly. Very helpful.