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
part out of the string, and store it in its own variable?
Asked
Active
Viewed 2.3k times
5
-
1As a sidenote, just a remark : the Referer is not always sent by the client (it can be disabled, for instance), and it can be faked. So, don't base any critical functionnality (nor security-oriented) on it ! – Pascal MARTIN Jul 17 '09 at 18:16
-
@PascalMARTIN Sound advice. But, I think a case could be made for examining HTTP_REFERER in $_SERVER (or, using filter_input() / filter_input_array()) from an HTTP POST request. – Anthony Rutledge Dec 16 '15 at 16:04
4 Answers
16
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" ];
}

Sampson
- 265,109
- 74
- 539
- 565
14
I'd use parse_url in the following way...
if ($urlParts = parse_url($myURI))
$baseUrl = $urlParts["scheme"] . "://" . $urlParts["host"];

HoLyVieR
- 10,985
- 5
- 42
- 67

Adam Wright
- 48,938
- 12
- 131
- 152
3
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.

Gumbo
- 643,351
- 109
- 780
- 844