Last active
September 2, 2021 08:53
-
-
Save geongeorge/c30e9b1e3e7590b8a22464c879ad9a04 to your computer and use it in GitHub Desktop.
Base64 URL safe, https://jsfiddle.net/magikMaker/7bjaT/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* use this to make a Base64 encoded string URL friendly, | |
* i.e. '+' and '/' are replaced with '-' and '_' also any trailing '=' | |
* characters are removed | |
* | |
* @param {String} str the encoded string | |
* @returns {String} the URL friendly encoded String | |
*/ | |
function Base64EncodeUrl(str){ | |
return str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''); | |
} | |
/** | |
* Use this to recreate a Base64 encoded string that was made URL friendly | |
* using Base64EncodeurlFriendly. | |
* '-' and '_' are replaced with '+' and '/' and also it is padded with '+' | |
* | |
* @param {String} str the encoded string | |
* @returns {String} the URL friendly encoded String | |
*/ | |
function Base64DecodeUrl(str){ | |
str = (str + '===').slice(0, str.length + (str.length % 4)); | |
return str.replace(/-/g, '+').replace(/_/g, '/'); | |
} | |
/** | |
* Example: | |
* This Base64 encoded string will be made URL friendly | |
*/ | |
var encoded = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA=='; | |
var url_encoded = Base64EncodeUrl(encoded); | |
var url_decoded = Base64DecodeUrl(url_encoded); | |
document.write(encoded + '<br />'); | |
document.write(url_encoded + '<br />'); | |
document.write(url_decoded + '<hr />'); | |
// "Test" | |
document.write(url_decoded === encoded); | |
PHP: | |
//Start cleaning url as in | |
// to decode base64 for url | |
//https://gist.github.com/geongeorge/c30e9b1e3e7590b8a22464c879ad9a04 | |
$file64 .= "==="; | |
$file64 = substr($file64,0,strlen($file64) + (strlen($file64)%4)); | |
$file64 = str_replace('-', '+', $file64); | |
$file64 = str_replace('_', '/', $file64); | |
$file64 = str_replace(',', '\\', $file64); | |
$url = urldecode(base64_decode($file64)); | |
//Stop cleaning url as in |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Node js as window.atob is not available in the node environment