How to encode URL in JS and Decode in PHP?
Solution 1
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.
Solution 2
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()
Comments
-
Ahmed Syed almost 2 years
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']
-
Gromski about 9 yearsWhy should your browser show "products.php%3Fprice_range%3D-INFto2000%2C2001to5000"?!
-
Ahmed Syed about 9 years@deceze For security purpose. :-)
-
-
prava about 9 yearsHow come its not working!!! Check this link - w3schools.com/jsref/jsref_decodeuricomponent.asp
-
Ahmed Syed about 9 years@satish rajak Though URL is encoded using encodeURIComponent, But PHP is not decoding it, error is
Undefined index: price_range
-
prava about 9 years@MujahedAKAS, definitely it won't show any error message. Check this URL - tools4noobs.com/online_php_functions/urldecode and add your generated encoded URI into here and check the output.
-
Ahmed Syed about 9 years@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? -
Saty about 9 yearscheck this link stackoverflow.com/questions/75980/…
-
Quentin about 9 years
urldecode($_GET['price_range']);
is wrong. PHP will decode data from URLs automatically before it puts the values into$_GET
-
Ahmed Syed about 9 yearsYes @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.