[Switch] PHP base64_encode URL address parameters used in the coding

Because the information base64_encode () string and into the request after I use public key encryption using the php openssl url in as a parameter, parameter urlencode (base64_encode ()), then urldecode () pass over the emergence +and =loss a string of cases, resulting in openssl decrypt base64_decode () failed.

We know that Base64 is one of the most common network for the transmission of 8Bit encoding byte code, is optimistic about the coding is not encrypted.
Encoding process is not explained, Base64 claim 8Bit the three bytes of each byte is converted to (3 6Bit of four 8 = 4 6 = 24), then add another two high 6Bit 0, consisting of four word 8Bit section, that is to say, string theory, converted to one-third longer than the original.

Format is uppercase and lowercase letters, numbers, the "=", "+" sign and "/" number
but "=" equals a maximum of only two
regular match is [[a-zA-Z0-9 = + /] + ]
Therefore, we see the case-letter string equal sign and one or two ends. Analyzing basically be base64 encoded
base64 not suitable for direct transmission as a parameter in the URL, base64 encoding found in the "/" "=" symbol. To solve this problem, the URL may be used for improving Base64 encoding, it is not the end of the filling '=' sign, and the standard Base64 "+" and "/" are changed to "_" and "-" , thus eliminating the need for conversion in the URL codec and database storage to be made.

By following function, the perfect solution to the problem of the base64 encoded url:

//url base64编码
function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

//url base64解码
function urlsafe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}
References
  1. PHP BASE64_ENCODE use on the URL address coding parameters

Guess you like

Origin www.cnblogs.com/fsong/p/11516470.html