Test if string is URL encoded in PHP

Psytronic picture Psytronic · Oct 28, 2009 · Viewed 111k times · Source

How can I test if a string is URL encoded?

Which of the following approaches is better?

  • Search the string for characters which would be encoded, which aren't, and if any exist then its not encoded, or
  • Use something like this which I've made:

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";

Answer

Irfan picture Irfan · Jun 17, 2010

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 :)