Security in PHP

Security in PHP

Secure the input

If you want a number exactly as a number in the input,pass it to is_numeric function.

var_dump(is_numeric("123.45"));//return bool(true)  
var_dump(is_numeric("string"));//return bool(false)

But we get data from the user in the form of string,and the inside the string,is a number.

For example,we have to deal with those:

  • a name
  • a data
  • an email
  • a link
  • a phone number

We can use filter_var function.It's take two parameter,the first is the data we want to check,the second is the ID of a filter.

  1. If you want to make sure our input is a vaild email,we use FILTER_VALIDATE_EMAIL
  2. If you validate the URL,use FILTER_VALIDATE_URL
  3. If you validate the int,use FILTER_VALIDATE_INT
  4. If you validate the float,use FILTER_VALIDATE_FLOAT

The filter IDs are prefixed with FILTER.Now here is other filter IDs can clean up the data for you,which start with the FILTER_SANITIZE.

echo filter_var("qwer",FILTER_SANITIZE_EMAIL);  

If you want to get rid of HTML tags,you should use FILTER_SANITIZE_STRING

echo filter_var("<p>Some Test</p>",FILTER_SANITIZE_STRING);//return Some Test  

There is one more secure function we going to talk about.It's used to prevent SQL Injection Attacks.We use mysql_real_escape_string("' OR ''='");.If you using a different database,the function may not be the same.