This article mainly introduces PHP to get the current execution of PHP file name code, the need for friends can refer to the following
Today write the wall when the navigation judge encountered this problem. My solution is this:
Judge the current PHP file name to determine which block of the navigation bar is highlighted.
How does php get the current URL file name?
That's what I'm dealing with: shock:
Tutorial
First of all, we must get the URL of the current page, where we use PHP to get the $_SERVER['PHP_SELF']
Web address
Suppose the URL is http://www.php.cn/
$php _self= $_server[' php_self ']; Get Web address//output result: http://www.php.cn/
The output found that we only need to index.php, the front of a large string of things are useless.
What do we do?
Here we use the substr () function.
substr()
is used to return a part of a string:
SUBSTR syntax
SUBSTR (String,start,length)
Parameters |
Description |
String |
Necessary. A string that specifies the part to return. |
Start |
Necessary. Specifies where to start the string.
Positive number – starts at the specified position of the string
Negative number – starts at the specified position starting at the end of the string
0– begins at the first character in a string
|
Length |
Optional. Specifies the length of the string to be returned. The default is until the end of the string.
|
See the second argument of this function, which specifies where the string begins. It is clear that the last/beginning of the URL is what we need.
Then we need to use the strrpos()
function to get/last occurrence position.
Strrpos syntax
Strrpos (String,find,start)
Parameters |
Description |
String |
Necessary. Specifies the string to be searched. |
Find |
Necessary. Specifies the character to find. |
Start |
Optional. Specify where to start the search. |
So the total code is as follows:
$php _self = substr ($_server[' php_self '],strripos ($_server[' php_self '], "/") +1);//Why add 1? Because I want to rule out the previous one.
One of the more recommended functions
Gets the current script URL function getcururl () { if (!empty ($_server["Request_uri"])) { $scriptName = $_server[" Request_uri "]; $nowurl = $scriptName; } else { $scriptName = $_server["Php_self"]; if (Empty ($_server["query_string"])) { $nowurl = $scriptName; } else { $nowurl = $scriptName. "?". $_server["Query_string"]; } } return $nowurl;}
This solves, in many cases, the need for some string intercept function help to get the results we want.
The above is the PHP to get the current execution of PHP file name code sample content, more relevant content please focus on topic.alibabacloud.com (www.php.cn)!