개발관련/PHP
[PHP]DB Insert 전 Query문 정화(?) 함수
파노카페
2012. 7. 18. 00:35
function mysql_prep( $value ) { // magic quotes gpc가 PHP 세팅에서 on으로 되어있는지 확인 // gpc는 get, post, cookie의 약자임 $magic_quotes_active = get_magic_quotes_gpc(); // PHP 버전 4.3.0 이상에서만 존재하는 mysql_real_escape_string 함수의 사용이 가능한지 확인 $new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0 if( $new_enough_php ) { // PHP v4.3.0 or higher // undo any magic quote effects so mysql_real_escape_string can do the work // 만약 magic quotes gpc의 PHP 세팅이 적용되었다면 magic quotes 적용을 취소하고 원래 상태로 되돌림 if( $magic_quotes_active ) { $value = stripslashes( $value ); } // mysql_real_escape_string 함수로 query문을 정화한다. $value = mysql_real_escape_string( $value ); } else { // before PHP v4.3.0 // if magic quotes aren't already on then add slashes manually // 만약 magic quotes gpc 세팅이 안 되어 있다면 addslashes 함수로 직접 정화한다. if( !$magic_quotes_active ) { $value = addslashes( $value ); } // if magic quotes are active, then the slashes already exist // 만약 magic quotes gpc 세팅이 적용되어 있다면 그냥 이 기능을 사용한다. } return $value; }이 기능을 사용하는 이유는 get, post, cookie를 통해 사용자에게 정보를 입력받을 때 그 정보에 SQL 문법을 망칠 수 있는 문자가 포함되어 있을 수 있기 때문이다. 예를 들어 사용자가 고의로 SQL 문을 입력하여 DB 데이터를 손상시킬 수도 있다. (SQL 인젝션) 위 함수를 사용하면 안전한 SQL문을 작성할 수 있다.