Magic Quotes
Воскресенье, 06 Мар 2011 19:33Posted in category PHP
Комментариев нет
Для тех, кто хочет автоматической обрабатывать GET, POST, Cookie и т.д. переменные:
Код экранирует все переменные! То есть, он эффективно предотвращает SQL инъекции и XSS attaks. Это снимает потребность в «magic_quotes_gpc = On» директивы.
Однако он рассматривает все переменные как текст, а не делать вид, освобождение номеров. Так он подходит только для создания SQL-запросов или отображения HTML-содержимого.
Следующий код может быть включен во все страницы, которые нуждаются в HTML и SQL обрабоку инъекция.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | <?php // escaping and slashing all POST and GET variables. you may add $_COOKIE and $_REQUEST if you want them sanitized. array_walk_recursive ( $_POST , 'sanitizeVariables' ); array_walk_recursive ( $_GET , 'sanitizeVariables' ); // sanitization function sanitizeVariables (& $item , $key ) { if (! is_array ( $item )) { // undoing 'magic_quotes_gpc = On' directive if ( get_magic_quotes_gpc ()) $item = stripcslashes ( $item ); $item = sanitizeText ( $item ); } } // does the actual 'html' and 'sql' sanitization. customize if you want. function sanitizeText ( $text ) { $text = str_replace ( "<" , "&lt;" , $text ); $text = str_replace ( ">" , "&gt;" , $text ); $text = str_replace ( "\"" , "&quot;" , $text ); $text = str_replace ( "'" , "&#039;" , $text ); // it is recommended to replace 'addslashes' with 'mysql_real_escape_string' or whatever db specific fucntion used for escaping. However 'mysql_real_escape_string' is slower because it has to connect to mysql. $text = addslashes ( $text ); return $text ; } // export POST variables as GLOBALS. remove if you want foreach ( array_keys ( $_POST ) as $ehsanKey ) $GLOBALS [ $ehsanKey ] = $_POST [ $ehsanKey ]; // export GET variables as GLOBALS. remove if you want foreach ( array_keys ( $_GET ) as $ehsanKey ) { $GLOBALS [ $ehsanKey ] = $_GET [ $ehsanKey ]; } // preventing the key used above for iteration from getting into globals (in case 'register_globals = On') unset( $ehsanKey ); // the reverse function of 'sanitizeText'. you may use it in pages which need the original data (eg for an HTML editor) function unsanitizeText ( $text ) { $text = stripcslashes ( $text ); $text = str_replace ( "&#039;" , "'" , $text ); $text = str_replace ( "&gt;" , ">" , $text ); $text = str_replace ( "&quot;" , "\"" , $text ); $text = str_replace ( "&lt;" , "<" , $text ); return $text ; } ?> |
Вы можете следить за ответами к этой публикации через RSS 2.0.
Вы можете оставить отзыв или трекбек со своего сайта.