How can I test if a string is URL encoded?
Which of the following approaches is better?
Here is something i just put together.
if ( urlencode(urldecode($data)) === $data){
echo 'string urlencoded';
} else {
echo 'string is NOT urlencoded';
}
I think there's no foolproof way to do it. For example, consider the following:
$t = "A+B";
Is that an URL encoded "A B" or does it need to be encoded to "A%2BB"?
What about:
if (urldecode(trim($url)) == trim($url)) { $url_form = 'decoded'; }
else { $url_form = 'encoded'; }
Will not work with double encoding but this is out of scope anyway I suppose?
send a variable that flags the decode when you already getting data from an url.
?path=folder/new%20file.txt&decode=1
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 :)
I am using the following test to see if strings have been urlencoded:
if(urlencode($str) != str_replace(['%','+'], ['%25','%2B'], $str))
If a string has already been urlencoded, the only characters that will changed by double encoding are % (which starts all encoded character strings) and + (which replaces spaces.) Change them back and you should have the original string.
Let me know if this works for you.