Reputation: 2363
I need to detect if a user is accessing my site from a certain sub-domain. How can I detect the following example and flag it using PHP? I only want to detect if "abc" is the sub-domain and nothing more, but it has to work with various other domains after "abc".
Yes, they're on the "abc" sub-domain.
No, they're not.
Upvotes: 1
Views: 272
Reputation: 19
You can configure your web server to redirect all your subdomains to a single PHP file where you can make up an error or redirect the user via the header()
function with something like...
header('Location: http://domain.com');
Also, because you're sure that the particular PHP file is being accessed because of a subdomain, then you can do something like...
$url = $_SERVER['SERVER_NAME'];
list($subdomain) = explode('.', $url, 2);
$subdomain = trim(strtolower($subdomain));
And then use the $subdomain
variable the way you like (eg. print it)...
echo $subdomain;
Just in case. For the Apache configuration, you need to modify the VirtualHost
for redirecting your subdomains to a PHP file for processing.
<VirtualHost *:80>
ServerAlias *.domain.com
DocumentRoot /website/directory/page.php
</VirtualHost>
NOTE
1.) To restart Apache.
2.) Apache will give you warning that the directory does NOT exist. It's true, because you are providing a file path instead of a directory path. But this will work.
Upvotes: 0
Reputation: 5981
<?php
if( explode( '.', $_SERVER['SERVER_NAME'] )[0] === 'abc' ) {
//do something
}
?>
That will explode server name in parts divided by .
, so it will compare the first part of the domain name with the string abc.
The explode(x,x)[N] thing is only possible in PHP 5.4+ (or 5.3+, I don't remember correctly).
Upvotes: 1
Reputation: 71422
You can access the host name from within the $_SERVER
superglobal like this:
$domain = $_SERVER['HTTP_HOST']
There are then any number of ways to determine if this value begins with abc
. The easiest might simply be stripos
if(stripos('abc', $domain) === 0) {
// you found it
}
Note that the use of ===
instead of ==
is VERY important here. If you used ==
and the substring was not found in $domain
, stripos
would return false
, which with == 0
would evaluate as true
in your conditional.
Upvotes: 1
Reputation: 1231
This will return the subdomain:
array_shift(explode(".",$_SERVER['HTTP_HOST']));
Upvotes: 2
Reputation: 27325
You can check the HTTP_HOST or SERVER_NAME in your $_SERVER variable.
<?php
if(strpos($_SERVER['SERVER_NAME'], 'abc.domain.com') !== false) {
//do something
}
?>
Upvotes: 2