Getting a specific part of an url into my php script?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jmansa
Forum Commoner
Posts: 81
Joined: Wed Aug 23, 2006 4:00 am

Getting a specific part of an url into my php script?

Post by jmansa »

I'm trying using "selfurl" and "basename" to get a certain part of the current url into my script, but cant figure it out... I want to get the part below marked with red into my script.
I have tryid with this, but I only get the last part of the url (welcome)

Code: Select all

function selfURL() {
	$s = empty($_SERVER["HTTPS"]) ? ''
		: ($_SERVER["HTTPS"] == "on") ? "s"
		: "";
	$protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s;
	$port = ($_SERVER["SERVER_PORT"] == "80") ? ""
		: (":".$_SERVER["SERVER_PORT"]);
	return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}
function strleft($s1, $s2) {
	return substr($s1, 0, strpos($s1, $s2));
}
$path = (selfURL());
$page = basename($path);
Can somebody please help me?!?
mentor
Forum Contributor
Posts: 100
Joined: Sun Mar 11, 2007 11:10 am
Location: Pakistan

Post by mentor »

Try this solution

Code: Select all

$url = "http://www.mypage.com/index.php/en/welcome";
$last_slash = strrpos($url, "/");
$temp = substr($url, 0, $last_slash);
$second_last_slash = strrpos($temp, "/");
echo substr($url, $second_last_slash+1, $last_slash-$second_last_slash-1);
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

dirname(), basename() and parse_url() may be of interest.
mentor
Forum Contributor
Posts: 100
Joined: Sun Mar 11, 2007 11:10 am
Location: Pakistan

Post by mentor »

Its easy with feyd's suggestion :wink:

Code: Select all

echo basename(dirname($url));
jmansa
Forum Commoner
Posts: 81
Joined: Wed Aug 23, 2006 4:00 am

Post by jmansa »

That did the job allmost... I want the result to come out as $page
I tryid like this but that doesnt work??? My head, my head...

Code: Select all

$url = selfURL();
$last_slash = strrpos($url, "/"); 
$temp = substr($url, 0, $last_slash); 
$second_last_slash = strrpos($temp, "/"); 
$page = echo substr($url, $second_last_slash+1, $last_slash-$second_last_slash-1);
Where am I going wrong???
Post Reply