Tutorial Example

PHP Base64 Encode String Safely: Replace +, / and = Characters – PHP Tutorial

When you are using base64 to encode a string, there are +, / and = characters in encoding result. In this tutorial, we will introduce how to replace +, / and = characters by encoding string with php base64. If you want to use python to do this, you can refer to this tutorial.

Improve Python Base64 to Encode String Safely: Replace +, / and = Characters- Python Tutorial

Encode a string safely

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

Decode a string safely

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

How to use?

Here we write an example to show how to use these two functions to encode and decode a string in php.

$str = 'https://www.example.com/c%c/c++/?id=1&p=3';
header('Content-Type: text/html; charset=utf-8');
$encode_safe = urlsafe_b64encode($str);
echo $encode_safe;
echo "\n";
$decode_safe = urlsafe_b64decode($encode_safe);
echo $decode_safe;

The result is:

aHR0cHM6Ly93d3cuZXhhbXBsZS5jb20vYyVjL2MrKy8_aWQ9MSZwPTM
https://www.example.com/c%c/c++/?id=1&p=3

From the result, we can find: