note 44748 added to security

From: Date: Sun, 15 Aug 2004 10:42:45 +0000
Subject: note 44748 added to security
Groups: php.notes 
Request: Send a blank email to php-notes+get-74686@lists.php.net to get a copy of this message
Not enough can be said about checking data that the user has submitted. Most new PHP programmers I come across suffer miserably from not doing any data validation. Almost all data should go through something like this: <?php //Alright, these are the variables we're expecting from the user. //This way we don't have to check for them later on. $initArr = array('var1', 'var2', 'var3', 'var4'); foreach($initArr AS $var) { if(!isset($_POST[$var])) {//If it's not set, set it $_POST[$var] = FALSE; } else {//Clean the variables we're expecting $_POST[$var] = cleanVar($_POST[$var]); } } //A general cleaning function. There may be times when you //don't want to use this, but not very often.... function cleanVar($var) { //If the variable is an array, we want to clean those values, too if(!is_array($var)) { $var = array($var); } foreach($var AS $key => $value) { $value = go_add_slashes($value); //Remove any HTML characters and replace them with the HTML entities $value= htmlspecialchars($value); //Remove any excess spacing in the beginning or end of the string $value = trim($value); $var[$key] = $value; } return $var; } //Magic quotes is enabled by default //But in the event that our scripts are on a server //that doesn't have them enabled, we'd be in big trouble //So we check for it //Without magic quotes, we are more vulnerable to SQL injection function go_add_slashes($var) { if(!is_array($var)) { $var = array($var); } if(!get_magic_quotes_gpc()) { foreach($var AS $key => $value) { //Add slashes if magic quotes gpc is turned off to prevent SQL injection $var[$key] = addslashes($value); } } return $var; } ?> ---- Manual Page -- http://www.php.net/manual/en/security.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+44748 Delete -- http://master.php.net/manage/user-notes.php?action=delete+44748&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+44748&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#74686) next »