Bastien
Bastien

Reputation: 189

PHP header location absolute URL

I came across an issue where an absolute path set in header location wouldn't work but pointing to the file itself did. This only affected a few customers. One of them was nice enough to try connecting through a VPN which made the header location work.

Didn't work:

header('Location: http://www.example.com' . $_SERVER['PHP_SELF']);

Works:

header('Location: ' . $_SERVER['PHP_SELF']);

Can anyone shine some light on this?

Thanks

Upvotes: 2

Views: 1590

Answers (2)

André Rabelo
André Rabelo

Reputation: 1

Also always exit the script afterwards because otherwise in my experience in certain circumstances code that comes after the redirect might still be executed. So a good example would look like this:

header("location:http://www.example.com/path/to/myfile.php");
exit;

Often you would use a server variable for this case:

$url = $_SERVER["HTTP_HOST"]."/path/to/myfile.php";
header("location:".$url);
exit;

Cheers!

Link answer: https://tousu.in/qa/?qa=1091514/

Upvotes: 0

TunaMaxx
TunaMaxx

Reputation: 1769

Your affected customers are not able to resolve the http://www.example.com (or whatever it actually is) URL for some reason. You can verify this by having them just try and visit the http://www.example.com by manually typing it in the browser location bar. That should fail too.

This can happen you have a site that is available under a number of domains, or directly by the IP address. Even www / non-www versions can make this happen. They hit the site at one domain or IP address that works for them, and then you try and redirect them to a URL they can not resolve. This explains why redirecting to just the path works, but an absolute URL doesn't.

If they can reach http://www.example.com in the browser, but not by redirect, ask them to blow out the browser cache.

Upvotes: 1

Related Questions