Ram Solanki
Ram Solanki

Reputation: 81

how to encode api URL using base64 in laravel?

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

Upvotes: 3

Views: 27768

Answers (2)

Vipertecpro
Vipertecpro

Reputation: 3274

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.

Upvotes: 3

Sodj
Sodj

Reputation: 969

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

Upvotes: 2

Related Questions