简体   繁体   中英

get current page not full url

Is it possible to save the current page in a variable (not the full url) using php

So if my page is www.mywebsite.com/news/bob

I am looking to get /bob in a variable.

 <?PHP $file_name = $_SERVER['PHP_SELF']; ?>

see this variable

$_SERVER['PATH_INFO']

maybe you need

basename($_SERVER['PATH_INFO']);

$_SERVER['PATH_INFO'] doesn't seem to exist on my install. Not sure what the story is there, but if it's not on mine, it may not be on yours so here's some alternatives.

$current_page = '/' . basename($_SERVER['PHP_SELF']);
$current_page = '/' . basename($_SERVER['REQUEST_URI']);
$current_page = '/' . basename($_SERVER['SCRIPT_NAME']);

I find $_SERVER['PHP_SELF'] to be quite dependable.

If you're fond of regular expressions you could try

$current_page = preg_replace('/(.*?\/)+(.*)$/', '/$2', $_SERVER['PHP_SELF']);

If you are using $_SERVER['PHP_SELF'] on included or required files, then it will return the current file, not the URL of the current page. On Windows machines, the only reliable options are $_SERVER['REQUEST_URI'] or $_SERVER['HTTP_X_ORIGINAL_URL'] however, these will include any querystring as well.

You would need to strip the query string off the end of the URL to get the part you want.

$current_page = $_SERVER['REQUEST_URI'];
$current_page = substr($current_page, 0, strpos($current_page, "?")); //removes query string
$current_page =  = '/' . array_pop(array_filter(explode("/", $current_page)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM