Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if page url has www in it or not with PHP?

Tags:

php

In PHP, how can I check if the current page has www in the url or not?

E.g if the user is on http://www.example.com/something , how can I find that there's www in the URL, and on http://example.com/something , www isn't in the url?

like image 679
Ali Avatar asked Nov 11 '12 23:11

Ali


3 Answers

You can use $_SERVER['HTTP_HOST'] to get your domain. Now, if your site does not use sub domains that's easy. Just use something like this:

$url1 = "www.domain.com";
$params = explode('.', $url1);

if(sizeof($params === 3) AND $params[0] == 'www') {
    // www exists   
}

Note that if your params array has 2 items, then domain looks like this domain.com and there is no www clearly. You can even check size of $params array and decide if there is www or not based on its size.

Now if your site uses sub domains then it get's more complicated. You would have these as possible scenarios:

$url1 = "www.domain.com";
$url2 = "www.sub.domain.com";
$url3 = "domain.com";
$url4 = "sub.domain.com";

Then you would again explode every url, and compare size and check if first item is 'www'. But note that your sub domain could be named www where www would be sub domain :D And then it would look like this: www.domain.com, and again, www is sub domain :) That's crazy I almost gone mad on this one :)

Anyway, to check for www when site is not using sub domains, that's peace of cake. But to check if url has www and your site is using sub domains, that could be tough. The simplest solution to deal with that problem would be to disable www sub domain, if you can.

If you need more help and this does not answer your question, feel free to ask. I had similar situation where users would be able to create their own accounts that would be sub domains, like www.user.domain.com, and I had to do the same thing.

Hope this helps!

like image 118
Matija Avatar answered Oct 13 '22 00:10

Matija


you could do a preg_match this would be:

if(preg_match('/www/', $_SERVER['HTTP_HOST']))
{
  echo 'you got www in your adress';
}
else
{
  echo 'you don not have www';
}

you could even do it with .htaccess depending on what you are building the above option would do fine for a simpel detection.

if you pick the option Ferdia gave do the check as following:

$domain = array_shift(explode(".",$_SERVER['HTTP_HOST']));
if(in_array('www', $domain))
{
    echo 'JUP!';
}
like image 22
John In't Hout Avatar answered Oct 13 '22 00:10

John In't Hout


Do you already know the url? Then take this:

<?php
$parsed = parse_url("http://www.example.com/something");
$hasWww = strpos($parsed['host'], "www.") === 0;
var_dump($hasWww);

Otherwise, take

 strpos($_SERVER['HTTP_HOST'], "www.") === 0
like image 36
David Müller Avatar answered Oct 12 '22 23:10

David Müller