Search code examples
phpvariablessubdomaindetection

Detect if a user is on a subdomain, and then add a variable using PHP?


I would like to know how to create a PHP IF Statement that detects if a user is loading/on a certain URL. In my case it's:

www.design.mywebsite.com

The IF Statement needs to cover the whole subdomain, EG the URL will also have to be detected:

www.design.mywebsite.com/filename.php

Once an IF statement is established, I want to add a PHP variable. So it might help others, let's call it:

$myvariable = "Hey there! You're on my subdomain";

So To Sum It Up: The final code should look something like this...

<?php
  if //Code to detect subdomain// {
    $myvariable = "Hey there! You're on my subdomain";
  }
?>

Solution

  • A simple solution is

    $host = "baba.stackoverflow.com"; // Your Sub domain
    
    if ($_SERVER['HTTP_HOST'] == $host) {
        echo "Hello baba Sub Domain";
    } else {
        echo "not baba domain";
    }
    

    You can also use parse_url http://php.net/manual/en/function.parse-url.php if you have the URL

    $url = "http://baba.stackoverflow.com/questions/10171866/detect-if-a-user-is-on-a-subdomain-and-then-add-a-variable-using-php";
    $info = parse_url($url);
    if ($info['host'] == $host) {
        echo "Hello baba Sub Domain";
    } else {
        echo "not baba domain";
    }
    

    Please replace $url with $_GET ;