상세 컨텐츠

본문 제목

[PHP] 문자열/배열 특수문자 치환/제거 (XSS 방어)

일상

by 행복 수집가 2019. 9. 26. 21:46

본문

320x100
반응형


특수문자 제거

함수설명
is_array
 - Finds whether a variable is an array // 변수가 배열인지 확인
is_scalar - Finds whether a variable is a scalar // 변수가 스칼라인지 확인
preg_replace - Perform a regular expression search and replace // 정규 표현식 검색과 치환을 수행
array_map — Applies the callback to the elements of the given arrays // 주어진 배열의 요소에 콜백을 적용

스칼라?
Scalar variables are those containing an integer, float, string or boolean. Types array, object and resource are not scalar.
스칼라 변수는 integer, float, string, boolean을 포함합니다. array, object, resource는 스칼라가 아닙니다.


문자열일경우 preg_replace 정규식으로 치환처리 할 수 있지만 
다중 배열 일 경우는 불가능하여 is_array로 배열인지 검사 후 
array_map 함수로 다시 special_chk함수를 호출하여 처리한다.

<?
function special_chk ($input) {
    if (is_array($input)) {
        return array_map('special_chk', $input);
    }
    else if (is_scalar($input)) {
        return preg_replace("/[ #\/\\\:;,'\"`<>()]/i", "", $input);
    }
    else {
        return $input;
    }
}

$text = "a<b:c'"; // 문자열
echo special_chk($text); 
// abc 출력


// 배열
$text_arr = array (
				'1'  => 'apple'
				,'2' => 'banana <script>'
				,'3' => '(melon):;'
				); 

print_r(special_chk($text_arr)); 
// Array ( [1] => apple [2] => bananascript [3] => melon ) 출력
?>



---------------------------------------------------------------------------------------------

php.ini filter 설정으로도 특수문자 처리 가능 


(htmlspecialchars 함수와 같은 기능 : htmlspecialchars — 특수 문자를 HTML 엔터티로 변환)
Filter all $_GET, $_POST, $_COOKIE, $_REQUEST and $_SERVER data by this filter. 
Original data can be accessed through filter_input().
(간단한 방법이나 특수문자가 모두 치환되어 잘 사용하지 않음 )

http://docs.php.net/manual/kr/filter.configuration.php

Be careful about the default flags for the default filters. 
You should explicitly set them to the value you want. 
For example, to configure the default filter to behave exactly like htmlspecialchars() you need to set them default flags to 0 as shown below.


php.ini 내에 filter 부분 주석 해제하여 사용.
[filter]
http://www.php.net/manual/en/filter.configuration.php#ini.filter.default
filter.default = full_special_chars

http://www.php.net/manual/en/filter.configuration.php#ini.filter.default-flags
filter.default_flags = 0

---------------------------------------------------------------------------------------------

htmlspecialchars 함수 
(http://docs.php.net/manual/kr/function.htmlspecialchars.php)

'&'(앰퍼샌드)는 '&'가 됩니다
'"'(겹따옴표)는 ENT_NOQUOTES를 설정하지 않았을 때 '"'가 됩니다.
'''(홑따옴표)는 ENT_QUOTES가 설정되었을 때만 '''가 됩니다.
'<'(미만)은 '<'가 됩니다.
'>'(이상)은 '>'가 됩니다.




728x90
반응형

관련글 더보기