InfiniteStack
InfiniteStack

Reputation: 458

Is it possible to determine whether "www." was entered as part of the URL into address bar purely from PHP?

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.

Upvotes: 0

Views: 67

Answers (2)

Mike B
Mike B

Reputation: 1446

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
    }

?>

Upvotes: 1

Duane Lortie
Duane Lortie

Reputation: 1260

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

Upvotes: 0

Related Questions