Extract Scheme and Host from HTTP_REFERER

后端 未结 4 1717
长情又很酷
长情又很酷 2020-12-11 19:30

I have $_SERVER[\'HTTP_REFERER\'] — pretend it is http://example.com/i/like/turtles.html. What would I need to do to get just the http://example.com

相关标签:
4条回答
  • 2020-12-11 20:17

    You should be able to use the parse_url function to achieve that

    0 讨论(0)
  • 2020-12-11 20:25

    You could use a regular expression:

    if (isset($_SERVER['HTTP_REFERER']) && preg_match('@^[^/]+://[^/]+@', $_SERVER['HTTP_REFERER'], $match)) {
        var_dump($match[0]);
    }
    

    Or you could use the parse_url function.

    0 讨论(0)
  • 2020-12-11 20:34

    I'd use parse_url in the following way...

    if ($urlParts = parse_url($myURI))
      $baseUrl = $urlParts["scheme"] . "://" . $urlParts["host"];
    
    0 讨论(0)
  • 2020-12-11 20:35

    In this example, the best solution would be to use PHP's parse_url method. This splits up the URL into an associative array. You would then build your final value by combining the scheme with the host:

    if ( $parts = parse_url( "http://example.com/i/like/turtles.html" ) ) {
        echo $parts[ "scheme" ] . "://" . $parts[ "host" ];
    }
    
    0 讨论(0)
提交回复
热议问题