5

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']

webaholik
  • 1,619
  • 1
  • 19
  • 30
Ahmed Syed
  • 1,179
  • 2
  • 18
  • 44

2 Answers2

3

You can use encodeURI() This function encodes special characters, except: , / ? : @ & = + $ #

To : , / ? : @ & = + $ # use encodeURIComponent()

Best way to encode all characters is to run both functions

var url = 'products.php?price_range=-INFto2000,2001to5000';
url = encodeURI(url);// Encode special characters
url = encodeURIComponent(url);//Encodes : , / ? : @ & = + $ # characters

By default php automatically decode Encoded URLs so you don't have to do anything. You can simply access URL parameters like this

 $_REQUEST['price_range'];

For some reasons if you have to decode URL Client side you can use decodeURI() & decodeURIComponent()

Skyyy
  • 1,539
  • 2
  • 23
  • 60
2

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.

webaholik
  • 1,619
  • 1
  • 19
  • 30
Saty
  • 22,443
  • 7
  • 33
  • 51
  • 1
    How come its not working!!! Check this link - http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp – prava Apr 02 '15 at 07:00
  • @satish rajak Though URL is encoded using encodeURIComponent, But PHP is not decoding it, error is `Undefined index: price_range` – Ahmed Syed Apr 02 '15 at 07:05
  • @MujahedAKAS, definitely it won't show any error message. Check this URL - http://www.tools4noobs.com/online_php_functions/urldecode/ and add your generated encoded URI into here and check the output. – prava Apr 02 '15 at 07:08
  • @satish rajak; Okay I did it this way; `window.location.href = 'products.php?price_range='+encodeURIComponent('-INFto2000,2001to5000');` and its working, is it right way to do this? – Ahmed Syed Apr 02 '15 at 07:17
  • check this link http://stackoverflow.com/questions/75980/best-practice-escape-or-encodeuri-encodeuricomponent – Saty Apr 02 '15 at 07:26
  • 4
    `urldecode($_GET['price_range']);` is wrong. PHP will decode data from URLs automatically **before** it puts the values into `$_GET` – Quentin Apr 02 '15 at 08:11
  • Yes @Quentin first I though URL is not encoded, because after encoding, without decoding everything was working fine, I thought changes are not effecting due to cookies or sometjng, But than I realized We dont need to decode it back in PHP. – Ahmed Syed Apr 02 '15 at 09:16