PHP code to get domain name from a URL

To get the domain name use this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$url = 'http://www.example.com/process.php?act=update&id=33'
 
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i', "http://www.php.net/index.html", $matches);
$host = $matches[1];
 
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
 
// host will return: www.example.com
// $matches[0] will return: example.com
?>

To get the script name use this

$_SERVER[‘SCRIPT_NAME’]

// will return: /process.php

and to get the parameters passed, use this

$_SERVER[“QUERY_STRING”]

// will return: act=update&id=33

Leave a Reply

Your email address will not be published. Required fields are marked *