How to get only the domain of a URL?

Asked

Viewed 719 times

6

The domain is not that of localhost.

If the user types a link, for example, http://exemplo.com/pasta/pasta2/past/ficheiro.php, i intend that PHP returns only this part of the url exemplo.com

  • Check the $_SERVER variable, it will return the values you need.

1 answer

18


PHP already has a function that separates all elements of a URL.

Is just the parse_url:

$url = 'http://exemplo.com/pasta/pasta2/past/ficheiro.php';
$elementos = parse_url($url);

echo $elementos['host']; // 'exemplo.com'

If you want a specific part use the second parameter:

echo parse_url($url, PHP_URL_HOST);  // 'exemplo.com'

See working on IDEONE.

These are the options for the second parameter:

 PHP_URL_SCHEME     // retorna string  - ex: http
 PHP_URL_HOST       // retorna string  - ex: site.com
 PHP_URL_PORT       // retorna inteiro - ex: 443
 PHP_URL_USER       // retorna string  - ex: admin
 PHP_URL_PASS       // retorna string  - ex: swordfish
 PHP_URL_PATH       // retorna string  - ex: /blog
 PHP_URL_QUERY      // retorna string  - ex: secao=esportes
 PHP_URL_FRAGMENT   // retorna string  - ex: ancora2


If using more than one part, take the entire array:

$partes = parse_url($url); // retorna array associativo

and use all the parts that matter:

echo $partes['scheme'].'://'.$partes['host'].$partes['path'];


More details in the manual:

http://php.net/manual/en/function.parse-url.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.