Test if string is URL encoded in PHP

前端 未结 13 2093
不思量自难忘°
不思量自难忘° 2021-01-01 11:10

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
相关标签:
13条回答
  • 2021-01-01 11:28

    Here is something i just put together.

    if ( urlencode(urldecode($data)) === $data){
        echo 'string urlencoded';
    } else {
        echo 'string is NOT urlencoded';
    }
    
    0 讨论(0)
  • 2021-01-01 11:30

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

    0 讨论(0)
  • 2021-01-01 11:32

    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?

    0 讨论(0)
  • 2021-01-01 11:32

    send a variable that flags the decode when you already getting data from an url.

    ?path=folder/new%20file.txt&decode=1
    
    0 讨论(0)
  • 2021-01-01 11:38

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

    0 讨论(0)
  • 2021-01-01 11:39

    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.

    0 讨论(0)
提交回复
热议问题