Skip to content

Instantly share code, notes, and snippets.

@Hexcles
Last active August 29, 2015 13:56
Show Gist options
  • Save Hexcles/8915724 to your computer and use it in GitHub Desktop.
Save Hexcles/8915724 to your computer and use it in GitHub Desktop.
URL安全的Base64编码(用'-'代替'+',用'_'代替'/',去掉末尾的padding),PHP实现
<?php
// public url_base64_encode(bin) {{{
/**
* url_base64_encode 生成URL安全的Base64编码
*
* @param string $bin
* @access public
* @return string
*/
function url_base64_encode($bin) {
$base64 = base64_encode($bin);
$base64 = str_replace('+', '-', $base64);
$base64 = str_replace('/', '_', $base64);
$base64 = str_replace('=', '', $base64);
return $base64;
}
// }}}
// public url_base64_decode(base64) {{{
/**
* url_base64_decode 解码URL安全的Base64
*
* @param mixed $base64
* @access public
* @return void
*/
function url_base64_decode($base64) {
$base64 = str_replace('-', '+', $base64);
$base64 = str_replace('_', '/', $base64);
/*
* Put the padding back (a little tricky)
* Base64 has one or two '=' at the end as padding.
* 3 bytes == 4 Base64 chars
* 1 byte left: two B64 chars and two '='
* 2 bytes left: three B64 chars and one '='
*/
$len = strlen($base64);
if ($len % 4 == 2) $base64 .= '==';
elseif ($len % 4 == 3) $base64 .= '=';
return base64_decode($base64);
}
// }}}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment