Jump to content

Auto Navigation Links using $_SERVER['REQUEST_URI']


themba

Recommended Posts

Hi Guys, I am not very experienced and I want to write a php function that will generate Links(Menu) as a user goes deeper navigating the website.

 

This is what I want to see being generated: Home >> weather >> addo for a url like this: http://mobi/weather/addo/

 

The first step would be to get the position for the occurrence of the character "/", then get the string in between the "/"

 

Well, I don't know how to about this for now...  :)

 

 

Basically, I wanted to generate a menu based on the user navigation or (Request URI), I spend the last hour trying to write this, it works as I wanted, but I need to clean it up, I am not a Guru, but this is how I managed to get to the solution:

 

function showNavigationPath()
{
//$request_uri = $_SERVER['REQUEST_URI'];
$request_uri = "About/Weather/Park/Addo/"; //Test URI
$current_url_length = strlen($request_uri);
$uri_split = str_split($request_uri);
$link_counter = 0;
$buffer = "";
for($i=0;$i<$current_url_length;$i++)
{
	$buffer .= $uri_split[$i];
	if($uri_split[$i] == "/") // Found a "/" in the URI String
	{
		$link[$link_counter] = $buffer;
		$buffer = "";
		$link_counter++;
	}
}
//echo($buffer); // Test

$link_counter = 0;
$final_nav = "<a href='/'>Home</a> "; // Buffer like store for Final out of the Navigation
foreach($link as $item)
{
	@$url .= $item;
	//echo("url[" . $c . "] " . $url[$c] . "<br /> ");
	$final_nav .= ">> <a href='" . $url ."'>$item</a> ";
	$link_counter++;
}
print("Final Nav: " . $final_nav);
}

For the URL: http://mobi/weather/addo/

 

The function returns this html code:

 

Final Nav: <a href='/'>Home</a> >> <a href='mobi/'>mobi/</a> >> <a href='mobi/weather/'>weather/</a> >> <a href='mobi/weather/addo/'>addo/</a>

Which is what I Basically wanted, you can check the code and help me improve, I am less experienced.  ;)

Well aside the fact that such URL can't exist...

 

This is not a complete code. Just read it and understand it.

$url_split = explode('.com',$url);
$url_params = explode('/', $url_split[1]);

$output = 'Final Nav: <a href="/">Home</a> >> ';

$nav_url = '';
foreach ($url_params as $param) {
     if (!empty($param)) {
          $nav_url .= $param . '/';
          $output .= '<a href="' . $nav_url . '">' . $param . '</a>';
     }
}

echo $output;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.