Checking for relative vs absolute paths/URLs in PHP

前端 未结 7 553
既然无缘
既然无缘 2021-01-17 15:45

I need to implement functions to check whether paths and urls are relative, absolute, or invalid (invalid syntactically- not whether resource exists). What are the range of

相关标签:
7条回答
  • 2021-01-17 16:34

    Since I cannot comment on answers because of my poor reputation I have to respond to ymakux answer with the function that he copied from Drupal library.

    I am using this function and I have found out that urls with query part (text after ? symbol) which contains | symbol will be evaluated to false

    for example:

    https://example.com/image.jpeg?fl=res,749,562,3|shr,,20|jpg,90
    

    Will be evaluated to false.

    All you have to do is add

    \|

    To query part of the regex so the function looks like:

    public static function isAbsoluteUrl($url)
        {
            $pattern = "/^(?:ftp|https?|feed)?:?\/\/(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*
            (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@)?(?:
            (?:[a-z0-9\-\.]|%[0-9a-f]{2})+|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]))(?::[0-9]+)?(?:[\/|\?]
            (?:[\w#!:\.\?\+\|=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})*)?$/xi";
    
            return (bool) preg_match($pattern, $url);
        }
    

    Hope it helps someone :)

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