Home >Backend Development >PHP Tutorial >How does php base64 encode and decode URL strings?

How does php base64 encode and decode URL strings?

青灯夜游
青灯夜游forward
2020-06-29 13:17:243240browse

How does php base64 encode and decode URL strings?

Base64 can transcode binary into visible characters for http transmission, but when base64 transcodes, it will generate " ", "/", "=", which are transcoded by the URL. Special characters cause inconsistency in the two aspects of data.

We can replace " ", "/", and "=" with characters that will not be transcoded in the URL before sending. After receiving the data, we can replace these characters back and then decode.

1. URL safe string encoding:

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

2. URL safe string decoding:

    function urlsafe_b64decode($string) {
       $data = str_replace(array('-','_'),array('+','/'),$string);
       $mod4 = strlen($data) % 4;
       if ($mod4) {
           $data .= substr('====', $mod4);
       }
       return base64_decode($data);
    }

Recommended tutorial: "php tutorial"

The above is the detailed content of How does php base64 encode and decode URL strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete