Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better SQL string sanitization function

Tags:

security

php

I am currently using below function to sanitize my $_POST and $_GET against SQL injection. Unfortunately, I cannot post code through it, for example: "<a href test". How does Twitter do it?

 function _secinput($variable)
 {return filter_var(mysql_real_escape_string($variable), FILTER_SANITIZE_STRING); }

Plus, can anyone tell suggest me if I can improve it in any ways?

like image 764
mahen23 Avatar asked Dec 12 '11 06:12

mahen23


2 Answers

There can never and will never be one function to sanitize everything. You must choose the right tool for the job.

1) htmlspecialchars($var,ENT_QUOTES) works well for most xss.

2) Parametrized query libraries like PDO and MySQLi work best for sql injection.

3) For CRLF injection, just remove new lines: str_replace("\n","",$var)

4) For Command injection use escapeshellarg()

And there are many other forms of injection.

like image 55
rook Avatar answered Oct 20 '22 06:10

rook


i just wanted to protect against sql injections

You merely can't "sanitize" all incoming data even against sql-injection only (and you shouldn't).

Even in this distinct case you SHOULD NOT "sanitize" your input variables altogether. There are different rules for the different parts of the query: you can't escape identifier the same way as data.

See this my answer with full explanation: https://stackoverflow.com/a/8255054/285587

like image 23
Your Common Sense Avatar answered Oct 20 '22 08:10

Your Common Sense