3

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

1
  • Thanx @Ankuraggrwal Commented Jan 25, 2017 at 11:24

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good solution. The 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.
2

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 );
});

2 Comments

You can generate $url from the base64 depending on how you generated it in the first place ... you can make it dynamic by generating it from current user or from date ... be creative
If the new base64 URL is static (always the same) i don't see why you should change it ... it's bad practice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.