1,105,290 Community Members

how to get certain part of url?

Member Avatar
nick3592
Light Poster
35 posts since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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?

Member Avatar
rajarajan07
Nearly a Posting Virtuoso
1,448 posts since May 2008
Reputation Points: 123 [?]
Q&As Helped to Solve: 242 [?]
Skill Endorsements: 3 [?]
 
0
 
<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
?>
<?php
  echo curPageURL();
?>

<!-- Sometimes it is needed to get the page name only. The following example shows how to do it: -->
<?php
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

Member Avatar
nick3592
Light Poster
35 posts since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
blocblue
Practically a Posting Shark
828 posts since Jan 2008
Reputation Points: 238 [?]
Q&As Helped to Solve: 162 [?]
Skill Endorsements: 16 [?]
Featured
 
0
 

Hi,

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.

R.

Member Avatar
nick3592
Light Poster
35 posts since Oct 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

thanks a lot

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article