0

Accessing the site without "www." counterpart in browser,

as in "site.com", will still echo "www.site.com" from $_SERVER['SERVER_NAME'];

This might seem like not a big deal, just determine this on front-end when making your ajax calls, using something like location.href, right?

Or simply remove "www." from SERVER_NAME. Good solution, but doesn't address the primary issue. Now PHP code must rely on JavaScript? Shouldn't back-end be able to determine yes-www vs no-www address?

Additionally, when you have <form action = "URL">, let alone PHP that generates code that must make calls to the server, the solution that uses $_SERVER['SERVER_NAME'] will produce cross-domain security errors.

So -- the question is -- is there a way in PHP to automatically determine whether www. part was or wasn't entered into the browser's address bar as part of the domain name?

The problem with this is that now you have server-side PHP code rely on JavaScript, that sometimes might be disabled in the browser. And that just in general, sounds like awkward practice.

InfiniteStack
  • 430
  • 2
  • 9
  • Your web server should probably be translating requests without `www.` into ones with `www.` (or vice-versa), so from that perspective everything should be being served on the same domain. – Matthew Herbst Aug 23 '16 at 18:42
  • Forcing rewrite from non-www to www. will have users say, "But http:// example.com is the mooodern way!" – InfiniteStack Aug 23 '16 at 18:49
  • So rewrite the other way. And for the record, `google.com` sends you to `www.google.com`. I'll happily do whatever Google does. – Matthew Herbst Aug 23 '16 at 18:53
  • suggest using a rewrite rule to either enforce with WWW, or without. ~edit, cant put code snippets in comments.. check my answer – Duane Lortie Aug 23 '16 at 18:56

2 Answers2

1

Yes this is entirely possible.

<?php 
    //Will be true if www. exists, and false if not. 

    $host_has_www = (strpos($_SERVER['HTTP_HOST'], 'www.') !== false) ? true : false;

    if ($host_has_www == true) { 
      //Do something
    }

?>
Mike
  • 1,436
  • 9
  • 16
  • 2
    This would also yield true, if the hostname would just _include_ 'www.', e.g. `subdomain.www.anothersubdomain.site.com`. You should check the position like `strpos(...) === 0`, or, my preference, `substr($host,0,4) === 'www.'` – Dan Soap Aug 23 '16 at 19:45
  • That's true, I actually made a mistake in asking the question:/ HTTP_HOST does accurately reflect the www. part in each case. I, by accident, was looking at a cached page that was cached from www-present domain. – InfiniteStack Aug 23 '16 at 20:57
0

To force www edit .htaccess

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

then every request will always have www or use a similar method to remove www

Duane Lortie
  • 1,285
  • 1
  • 12
  • 16