How to implement base64 encoding and decoding in PHP?

In PHP, you can use the base64_encode() function to encode a string in base64, and the base64_decode() function to decode it. Below are some sample codes:

// 示例字符串
$str = 'Hello World!';

// 进行base64编码
$encodedStr = base64_encode($str);
echo $encodedStr; // 输出:SGVsbG8gV29ybGQh

// 进行base64解码
$decodedStr = base64_decode($encodedStr);
echo $decodedStr; // 输出:Hello World!

It is important to note that the base64 encoded string may contain characters that are not allowed in URL, such as “+” and “/”. To safely transmit a base64 encoded string in a URL, one can use base64url encoding by replacing “+” with “-” and “/” with “_”.

Here is an example code for encoding and decoding using base64url.

// 示例字符串
$str = 'Hello World!';

// 进行base64url编码
$encodedStr = str_replace(['+', '/'], ['-', '_'], base64_encode($str));
echo $encodedStr; // 输出:SGVsbG8gV29ybGQh

// 进行base64url解码
$decodedStr = base64_decode(str_replace(['-', '_'], ['+', '/'], $encodedStr));
echo $decodedStr; // 输出:Hello World!

I hope this is helpful to you!

bannerAds