Search code examples
phpbase64slash

How to encode base_64 without slash in PHP?


Orignal String:

$string = "Home/Gallery/Images/Mountains";

Then I encode this string into base64_encode():

echo base64_encode($string);

Output:

SG9tZS9HYWxsZXJ5L0ltYWdlcy9Nb3VudGFpbnM=

But I want to show this output:

SG9tZS9H/YWxsZXJ5L0lt/YWdlcy9Nb3V/udGFpbnM=


Look at the Slashes

means I don't want to that base64_encode() never encode a slash "/" and show slash in orignal form but other string always convert into base64_encode()

There is someone here who can answer me and please also tell how to decode?

(Sorry for bad english)


Solution

  • You can split it and use the single parts to encode. You can not exclude any chars.

    Note, you will gain some extra padding bytes!

    $string = "Home/Gallery/Images/Mountains";
    
    echo join('/', array_map(fn($v) => base64_encode($v), explode('/', $string)));
    

    SG9tZQ==/R2FsbGVyeQ==/SW1hZ2Vz/TW91bnRhaW5z