Get domain with PHP using parse_url

Asked

Viewed 150 times

3

I need to check if the page accessed is in the domain .com.br or .fr.

I thought I’d use the function parse_url but I did not succeed, how to take only the part .com.br or .fr.

For example if the domain is.

https://www.exemplo.com.br

He returns to me www.exemplo.com.br catching the PHP_URL_HOST I needed you to take just a p .com.br

And the same goes for domain

https://www.exemplo.fr

Take only the .fr

  • 1

    The information .com.br or .fr are part of the host, the function plays its role correctly. You need to manipulate the string to extract the result you need, but you need to think about aspects that can complicate it. Ex: you can separate by stitch and remove the first 2 elements. So www.exemplo.com.br would be com.br, but this same logic does not apply if the URL has more depth subdomains. Ex.: static.app.exemplo.com.br stick around exemplo.com.br, which is not the outcome you expect. So I suggest you clarify for us your ideal answer idea for us to help.

  • After picking up the full url as you can already do, use the function explode() to break your string everywhere it has points, this function will return you an array of strings, if you take the last position, you can check if it is . fr or .br... http://php.net/manual/en/function.explode.php

  • Another way is also to check whether .fr is part of the outcome of parse_url using the command preg_match()

  • I totally get what you mean, I don’t know why you closed the question. Anyway I already left the computer after answering the question if they reopen the question or put as comment.

  • Already tried http://php.net/manual/en/function.parse-url.php#83828 ?

  • @Luizfernando can send a comment.

  • <?php&#xA;$url = "https://www.php.br";&#xA;echo " A url é: $url\n";&#xA;echo "\nO tipo de domínio da URL é: " . getSufixoUrl($url);&#xA;function getSufixoUrl($url) {&#xA; $explode_url = explode(".", $url, 3);&#xA; $count = count($explode_url);&#xA;&#xA; if ($count === 3) {&#xA; $tipo_dominio = "." . $explode_url[2];&#xA; } elseif ($count === 2) {&#xA; $tipo_dominio = "." . $explode_url[1];&#xA; }&#xA; return $tipo_dominio;&#xA;} The function considers the domain to be www.exemplo.com. If you don’t put www, you have to change the values. If you want to restrict only .com.br and . fr change in return tbm

Show 2 more comments
No answers

Browser other questions tagged

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