Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if string is URL encoded in PHP

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";
like image 307
Psytronic Avatar asked Oct 28 '09 14:10

Psytronic


People also ask

How do you check if a URL is encoded?

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.

Is URL encoded PHP?

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.

Is URL encoded?

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.

Does PHP automatically decode URL?

Yes, all the parameters you access via $_GET and $_POST are decoded.


1 Answers

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

like image 156
Irfan Avatar answered Oct 06 '22 02:10

Irfan