hi i was wondering how i can get a certain part of a url in php. For example a url like http://site.com/randomfile.
what i want is only the site.com part. How can i do this?

Recommended Answers

All 4 Replies

Member Avatar
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
 } else {
 return $pageURL;
  echo curPageURL();

<!-- Sometimes it is needed to get the page name only. The following example shows how to do it: -->
function curPageName() {
 return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);

echo "The current page name is ".curPageName();

The above code displays the current url and extract the filename from the url

Also look into the manual for substr function http://php.net/manual/en/function.substr.php

what i meant is getting the certain part a url from a string after a user inputs it, sorry for not mentioning earlier.


A more suitable method to look at might be parse_url.

Specifically, to get the host name out of a URL you would use:

$strUserUrl = 'http://www.example.com/this/is/a/page.html';
$strHost = parse_url($strUserUrl, PHP_URL_HOST);
// $strHost = www.example.com

Or you could use the method without specifying a single component and it'll return an array breakdown of the URL.


thanks a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.