PHP validation/regex for URL

后端 未结 21 2086
青春惊慌失措
青春惊慌失措 2020-11-22 01:19

I\'ve been looking for a simple regex for URLs, does anybody have one handy that works well? I didn\'t find one with the zend framework validation classes and have seen sev

21条回答
  •  -上瘾入骨i
    2020-11-22 01:50

    function is_valid_url ($url="") {
    
            if ($url=="") {
                $url=$this->url;
            }
    
            $url = @parse_url($url);
    
            if ( ! $url) {
    
    
                return false;
            }
    
            $url = array_map('trim', $url);
            $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
            $path = (isset($url['path'])) ? $url['path'] : '';
    
            if ($path == '') {
                $path = '/';
            }
    
            $path .= ( isset ( $url['query'] ) ) ? "?$url[query]" : '';
    
    
    
            if ( isset ( $url['host'] ) AND $url['host'] != gethostbyname ( $url['host'] ) ) {
                if ( PHP_VERSION >= 5 ) {
                    $headers = get_headers("$url[scheme]://$url[host]:$url[port]$path");
                }
                else {
                    $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
    
                    if ( ! $fp ) {
                        return false;
                    }
                    fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n");
                    $headers = fread ( $fp, 128 );
                    fclose ( $fp );
                }
                $headers = ( is_array ( $headers ) ) ? implode ( "\n", $headers ) : $headers;
                return ( bool ) preg_match ( '#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers );
            }
    
            return false;
        }
    

提交回复
热议问题