5

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";
  }
?>
5
  • 1
    This has already been asked: stackoverflow.com/questions/5292937/…
    – Manuel
    Apr 16, 2012 at 9:49
  • Hi there dragon112. I have already looked at that, and yes I was aware of it - but I'm a bit confused as to how I would turn it into a PHP IF Statement. Apr 16, 2012 at 9:51
  • Thanks for commenting so quickly ogur :). I know that it will require a parse_url(), but I'm not sure where to go from there. Apr 16, 2012 at 9:53
  • 1
    Well I guess you have to check if array returned from parse_url() (or exploded parts of that array) contains subdomain name you look for, am I right?
    – ogur
    Apr 16, 2012 at 9:59
  • I think that would have a fair chance at working. Do you reckon you can show me how it's done though as an answer? Cheers. Apr 16, 2012 at 10:05

1 Answer 1

14

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 ;

1
  • 2
    Outstanding answer - couldn't have asked for better. Worked like a charm. Thank you very much Baba. Apr 16, 2012 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.