Yuseferi
Yuseferi

Reputation: 8710

get domain name only in not full path

I know I can parse full url with parse_url in php, but my problem is when I have not full url ormat, how can I get domain name.

my urls are in 2 condtion sometimes in full path and sometimes in not full path,

as example
blahblah.com/ddddd/fffff/a.php?ddddd
http://blahblah.com/ddddd/fffff/a.php?ddddd

I want it return me blahbla.com

my url is not browser url,treat them like a variable not current url

Upvotes: 2

Views: 1343

Answers (7)

Udara Herath
Udara Herath

Reputation: 885

Try this,

    $uri = $_SERVER['REQUEST_URI']; // $uri == example.com/index
    $exploded_uri = explode('/', $uri); //$exploded_uri ==     array('example.com','index')
    $domain_name = $exploded_uri[0]; //$domain_name = 'example.com'

Upvotes: 0

The right way to achieve this is by making use of $_SERVER['HTTP_HOST'];

Upvotes: 1

Krish R
Krish R

Reputation: 22721

Try this,

$url='blahblah.com/ddddd/fffff/a.php?ddddd';
$Urls = parse_url($url);        
if(!isset($Urls['host'])){          
   $url = 'http://'.$url;
   $Urls = parse_url($url);
}       
echo $Urls['host'];

Upvotes: 0

Oleg Dubas
Oleg Dubas

Reputation: 2348

The best and official way to do it would be using parse_url() But in your particular case you need a trick:

$url = 'http://'.preg_replace('!^https?://!i', '', $url);
  1. First, you intentionally make sure there's no http:// or https:// at the beginning.
  2. THEN you add your own http:// at the beginning
  3. And NOW this $url is finally eligible for parse_url():

echo parse_url( $url, PHP_URL_HOST );

Upvotes: 0

Yuseferi
Yuseferi

Reputation: 8710

tricky way :)

 $url_p=  parse_url($url);

    if(!isset($url_p['scheme'])){
        $url='http://'.$url;
        $url_p=parse_url($url);
    }
echo $url_p['host'];

Upvotes: 0

Tims
Tims

Reputation: 2007

use

echo $_SERVER['SERVER_NAME'];

or to remove 'www.' use

echo str_replace('www.', '', $_SERVER['SERVER_NAME']);

Upvotes: 1

user1844933
user1844933

Reputation: 3427

try this

echo $_SERVER['SERVER_NAME'];

Upvotes: 1

Related Questions