How to pass base64 encoded strings in URL with PHP?

Spread the love

Sometimes, we want to pass base64 encoded strings in URL with PHP.

In this article, we’ll look at how to pass base64 encoded strings in URL with PHP.

How to pass base64 encoded strings in URL with PHP?

To pass base64 encoded strings in URL with PHP, we can use the base64_encode function to encode the string.

For instance, we write

function base64_url_encode($input)
{
    return strtr(base64_encode($input), "+/=", "._-");
}

function base64_url_decode($input)
{
    return base64_decode(strtr($input, "._-", "+/="));
}

to define the base64_url_encode and base64_url_decode functions.

In base64_url_encode, we call base64_encode with $input to encode the $input string into base64.

We use strtr to replace '+', '/' and '=‘ with '.', '-', and '-' respectively.

Likewise, we create the base64_url_decode function that decodes the base64 encoded $input string.

We replace the characters with strtr before we decode the string.

Conclusion

To pass base64 encoded strings in URL with PHP, we can use the base64_encode function to encode the string.

Leave a Reply

Your email address will not be published. Required fields are marked *