Data Encoding Tutorials - Herong's Tutorial Examples - v5.22, by Herong Yang
PHP Implementation of Base64URL Encoding
This section provides a tutorial example on how to perform Base64URL encoding on binary files using my own implementation in PHP.
Unfortunately, Perl does not provide any default implementation of Base64URL encoding. So we have to do it ourself.
Here is a sample program that allows you to perform Base64URL encoding/decoding and other variations.
<?php # Base64_Tool.php # Copyright (c) 2010 HerongYang.com. All Rights Reserved. if (count($argv)<5) { print("Usage:\n"); print("php Base64_Tool.php mode standard input output\n"); exit; } $mode = $argv[1]; $standard = $argv[2]; $inputFile = $argv[3]; $outputFile = $argv[4]; $inputStream = fopen($inputFile, "rb"); $inputBytes = fread($inputStream, filesize($inputFile)); fclose($inputStream); $outputBytes = ""; if ($mode=="decode") { if ($standard=="url") { $inputBytes = strtr($inputBytes, "-_", "+/"); } $outputBytes = base64_decode($inputBytes); } else { $outputBytes = base64_encode($inputBytes); if ($standard=="mime") { $outputBytes = chunk_split($outputBytes, 76, "\r\n"); } else if ($standard=="url") { $outputBytes = strtr($outputBytes, "+/", "-_"); $outputBytes = rtrim($outputBytes, "="); } } print($outputBytes."\n"); $outputStream = fopen($outputFile, "wb"); fwrite($outputStream, $outputBytes); fclose($outputStream); ?>
Let's try it with different test cases:
herong$ php Base64_Tool.php encode url A.txt encoded.txt QQ herong$ php Base64_Tool.php decode url encoded.txt decoded.txt A herong$ php Base64_Tool.php encode url lazy_dog.txt encoded.txt VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZy4= herong$ php Base64_Tool.php decode url encoded.txt decoded.txt The quick brown fox jumps over the lazy dog. herong$ php Base64_Tool.php encode url url.txt encoded.txt aS5odG0_NjQ-NjM herong$ php Base64_Tool.php decode url encoded.txt decoded.txt i.htm?64>63 herong$ php Base64_Tool.php encode standard url.txt encoded.txt aS5odG0/NjQ+NjM= herong$ php Base64_Tool.php decode standard encoded.txt decoded.txt i.htm?64>63 herong$ php Base64_Tool.php encode url icon.png encoded.txt iVBORw0KGgoAAAANSUhEUgAAABgAAAAY ... HwXgCfzQYOFCEQYGAAAAAElFTkSuQmCC herong$ php Base64_Tool.php decode url encoded.txt decoded.txt ?PNG...
As you can see, my implementation of Base64URL in PHP works as expected.
Table of Contents
Base64 Encoding and Decoding Tools
►Base64URL - URL Safe Base64 Encoding
Java Built-In Implementation of Base64URL
Python Built-In Implementation of Base64URL
►PHP Implementation of Base64URL Encoding
Perl Implementation of Base64URL Encoding