Encode and Decode query string value in php

10

When developing a search module/ filter for some kind of listing that will be accessible to public it is advised not to show the actual ID of the data, user may use the ID to do some notorious stuff. In this tutorial I will be explaining how to encode and decode query string value in PHP.

When making a CRUD application (Create, read, update, delete) you will come across GET and POST methods for processing data. POST is secure and used for saving, updating or deleting data. But when we need to fetch data from database on the basis of some filter, we use GET method. Let’s take an example where you want to filter a products listing on the basis of category ID. In this case we use GET method. So a sample url be like www.example.com/products.php?cat=1

We then use that query parameter cat value and process the results. But displaying the ID to the user may not be a good IDEA in all cases. So what do we do? We obfuscate/encode the value. Let us see how we do this.

Encode and decode string using php

We can use base64_encode and base64_decode function to achieve our desired results. First we encode the category id and add it to a hyperlink. You can use it in a form and bind it to an input as well.

So when the user clicks on the hyperlink the category ID which is ‘1’ display and ‘MQ==’ as an encoded string. Now it’s time to decode it.

This does what we are looking for, BUT DID YOU NOTICE SOMETHING? The ‘==’ at the end the value when we encode the category id, ‘=’ at the end or in the middle of a value can sometime cause problem when we have multiple query string parameters. SO WHAT TO DO? Simply extending the function will do the trick. We will use strtr function to replace the unwanted characters with some dummy characters. Take a look at the two custom made function below.

The functions are set, let’s use them now. Just like the above example where we passed category ID but in this case using our own custom functions.

To decode the value is as easy like the earlier one, just change the function name.

If you guys have any better workaround, do share with us.

Share.
 

About Author

Entrepreneur & Dreamer

I am a passionate Software Professional, love to learn and share my knowledge with others.

Software is the hardware of my life.

10 Comments

Leave A Reply

CommentLuv badge

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.