I have a simple webpage with a simple menu.
Each page of the webpage (for example, index.php, page-01.php etc) pulls the menu in using the include function:
<?php
include 'menu.php';
?>
I want the menu item for the current page formatted, so I’m trying to get the menu to check the name of the current page. For example, when I’m on index.php, I want a function in menu.php to return "index".
I tried using this in menu.php:
echo basename(__FILE__, '.php');
But it returns "menu" instead (which in retrospect, makes a lot of sense).
What can I use in my menu.php file to return the current page name?
Thanks!
2
Answers
You can define a function in the included file and call it with the current file name:
index.php, page-01.php, page-02.php…:
menu.php:
You can use
$_SERVER['REQUEST_URI']
to get the path and query fragments of the URL as entered by user (/blog/technology/latest?limit=10
),$_SERVER['SCRIPT_NAME']
to get the script file path relative to document root (/blog/show-category.php
) and$_SERVER['SCRIPT_FILENAME']
to get the full path on server’s disk (/var/www/public/blog/show-category.php
). I think all these are pretty much standard across all server APIs, but it won’t hurt to check in your server (runphpinfo()
for a quick peek).There’s no general solution to map URLs to menu items since you can essentially code whatever structure you want. In the worst case, you’ll have to store a map somewhere, maybe an array you also use to build the menu:
If your project follows a legacy structure where individual scripts are just referenced in the URL, it should be straightforward.