how to encode URL using base64 in laravel?
I need something like this:
original URL: http://localhost/dashboard/api/test/
encode URL: http://localhost/dashboard/YXBpL3Rlc3Qv
I've found this piece of code which helped me, I'm just looking for something that removes "=" from base64 string so here :-
<?php
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
?>
Example :-
dump(rtrim(strtr(base64_encode('Hello World'), '+/', '-_'), '='));
$encodedString = rtrim(strtr(base64_encode('Hello World'), '+/', '-_'), '=');
dd(base64_decode(str_pad(strtr($encodedString, '-_', '+/'), strlen($encodedString) % 4, '=')));
I hope this helps someone.
str_pad() however is both incorrect and unnecessary here. A padding is never added because % 4 is always < 4 and the passed string is most likely longer than 4 characters. Also base64_decode() does not case about the '=' padding at the end.If you're using Routes you can do it like this:
Route::get('/dashboard/{code}', function($code){
$url = base64_decode($code);
//redirect according to $url ... for example "api/test/"
return redirect( $url );
});