본문 바로가기
Infomation

PHP Javascript urlencode 처리 관련

by Happens 2022. 11. 30.
반응형
PHP Javascript urlencode 처리 관련

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

 

encodeURI() - JavaScript | MDN

The encodeURI() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surroga

developer.mozilla.org

A–Z a–z 0–9 - _ . ! ~ * ' ( )

; / ? : @ & = + $ , #

PHP와 Javascript의 urlencode처리가 다르다.

Javascript의 경우 Encode시 제외하는 문자가 존재하는데

그렇기 때문에  decodeURI/encodeURI 함수를 사용하면 둘의 차이가 발생한다. 

function urlencode(str) {
    str = (str + '').toString();
    return encodeURIComponent(str)
        .replace(/!/g, '%21')
        .replace(/'/g, '%27')
        .replace(/\(/g, '%28')
        .replace(/\)/g, '%29')
        .replace(/\*/g, '%2A')
        .replace(/%20/g, '+');
}
 
function urldecode(str) {
    return decodeURIComponent((str + '')
        .replace(/%(?![\da-f]{2})/gi, function() {
            return '%25';
        })
        .replace(/\+/g, '%20'));
}
 
function rawurlencode(str) {
    str = (str + '').toString();
    return encodeURIComponent(str)
        .replace(/!/g, '%21')
        .replace(/'/g, '%27')
        .replace(/\(/g, '%28')
        .replace(/\)/g, '%29')
        .replace(/\*/g, '%2A');
}
 
function rawurldecode(str) {
    return decodeURIComponent((str + '')
        .replace(/%(?![\da-f]{2})/gi, function() {
            return '%25';
        }));
}

위 코드를 사용하여 통일이 가능하다.

추가적으로 urlencode와 rawurlencode의 차이는 공백의 처리방식만 다르다.

urlencode의 경우 공백을 +로 처리하고 rawurlencode의 경우 %20으로 처리를 한다.

 

 

반응형