How to encode URL in JS and Decode in PHP?

Ahmed Syed picture Ahmed Syed · Apr 2, 2015 · Viewed 11.2k times · Source

Following is my JS code:

window.location.href = 'products.php?price_range=-INFto2000,2001to5000';

My question is how do I encode the URL in javascript & decode it in PHP, such that my browser's navigation bar will show

"products.php?price_range=-INFto2000%2C2001to5000"

instead of

"products.php?price_range=-INFto2000,2001to5000"

and my php code will be able to work with the proper value of -INFto2000,2001to5000 in $_GET['price_range']

Answer

Saty picture Saty · Apr 2, 2015

Try this in your javascript code

window.location.href = 'products.php?price_range='+encodeURIComponent('-INFto2000,2001to5000');

You can access the decoded value in $_GET['price_range']. $_GET variables are decoded by default in PHP.