Best PHP security for MySql injection, XSS,...?

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
ExSilencer
Forum Newbie
Posts: 1
Joined: Thu Jan 20, 2011 11:37 am

Best PHP security for MySql injection, XSS,...?

Post by ExSilencer »

I was searching around for some good security regarding forms in PHP which data is then written to MySql.

I get some value from URL or form this way:
$something = $_GET['something']; or $something = $_POST['something'];

This can be exploited then by mysql injection and XSS,... right?

Well I was searching for best solution for that and I am wondering if I use this code, will it be OK?

$something = mysql_real_escape_string(htmlspecialchars(stripslashes(strip_tags($_GET['something']))));

Or should I use them seperatly?
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Best PHP security for MySql injection, XSS,...?

Post by AbraCadaver »

Depends on what you are doing, displaying data, inserting data into the database and what is acceptable. Normally you would use htmlentities() when displaying data to make sure there is no HTML/Script data. You should always use mysql_real_escape_string() when inserting into the database. You only need stripslashes() on user data (POST, GET, etc.) if your server uses magic_quotes. You only need to use strip_tags() if you are positive that you don't want any HTML.

Example:

Code: Select all

// store in db
    if(get_magic_quotes_gpc()) {
        $var = stripslashes($var);
    }
    $var = mysql_real_escape_string($var);

// display when HTML not needed
    $var = htmlentities($var);
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply