Redirect to WWW using PHP

Translations: "Română" |

Share on:

The problem occurs when the user is accessing a domain name and he must be redirected to the same domain name, keeping the GET variables but with WWW in front.

My solution is based on the header function and global variables in $ _SERVER:

 1// I'm storing the address for later use 
 2// it will be like 'www.exemple.org' or 'exemple.org'
 3$host = $_SERVER['HTTP_HOST'];
 4
 5// checking if the firs 4 characters are 'www.'
 6// '.' is important for domain names that start with 'www'
 7if(substr($host, 0, 4) !== 'www.') {
 8     // announce the browser that the page was moved
 9     header('HTTP/1.1 301 Moved Permanently'); 
10
11     // the new location
12     // the GET variables are in $_SERVER['REQUEST_URI'] 
13     header('Location: http://www.' . $host . $_SERVER['REQUEST_URI']);
14
15     // exiting the page
16     exit();
17}

Because of the 301 header the search engines will no longer index the page with out www.

PS: the code above should be the first thing that is output on the page!