How can I test if a string is URL encoded?
Which of the following approaches is better?
function is_urlEncoded($string){ $test_string = $string; while(urldecode($test_string) != $test_string){ $test_string = urldecode($test_string); } return (urlencode($test_string) == $string)?True:False; } $t = "Hello World > how are you?"; if(is_urlEncoded($sreq)){ print "Was Encoded.\n"; }else{ print "Not Encoded.\n"; print "Should be ".urlencode($sreq)."\n"; }
The above code works, but not in instances where the string has been doubly encoded, as in these examples:
$t = "Hello%2BWorld%2B%253E%2Bhow%2Bare%2Byou%253F";
$t = "Hello+World%2B%253E%2Bhow%2Bare%2Byou%253F";
So you can test if the string contains a colon, if not, urldecode it, and if that string contains a colon, the original string was url encoded, if not, check if the strings are different and if so, urldecode again and if not, it is not a valid URI.
PHP | urlencode() Function. The urlencode() function is an inbuilt function in PHP which is used to encode the url. This function returns a string which consist all non-alphanumeric characters except -_. and replace by the percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.
URL Encoding (Percent Encoding) URLs can only be sent over the Internet using the ASCII character-set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.
Yes, all the parameters you access via $_GET and $_POST are decoded.
i have one trick :
you can do this to prevent doubly encode. Every time first decode then again encode;
$string = urldecode($string);
Then do again
$string = urlencode($string);
Performing this way we can avoid double encode :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With