This article mainly introduces PHP code for obtaining the name of the currently executed php file. For more information, see the following article. it mainly introduces PHP code for obtaining the name of the currently executed php file. For more information, see
This problem occurs in the navigation judgment when I write the confession wall today. My solution is as follows:
Determine the current php file name to determine the highlight of the navigation bar.
So how does php get the current url file name?
I handle it like this: shock:
Tutorial
First, you must obtain the URL of the current page. here we use the php$_SERVER['PHP_SELF']
To obtain the webpage address.
Assume that the url is #
$ Php_Self = $ _ SERVER ['php _ SELF ']; // Obtain the webpage address // output result :#
After the output, we found that we only need index. php, and the previous one is useless.
What should we do?
Here we use the substr () function.
substr()
Is a part of the returned string:
Substr syntax
Substr (string, start, length)
Parameters |
Description |
String |
Required. Specifies that a part of the string is to be returned. |
Start |
Required. Specifies where the string starts.
Positive number-start at the specified position of the string
Negative number-start at the specified position starting from the end of the string
0-start at the first character in the string
|
Length |
Optional. Specifies the length of the string to be returned. The default value is until the end of the string.
|
The second parameter of the function specifies where the string starts. Obviously, the last/start in the url is what we need.
So we need to use strrpos()
Function.
Strrpos syntax
Strrpos (string, find, start)
Parameters |
Description |
String |
Required. Specifies the string to be searched. |
Find |
Required. Specifies the characters to be searched. |
Start |
Optional. Specifies where to start searching. |
The code is as follows:
$ Php_Self = substr ($ _ SERVER ['php _ SELF '], strripos ($ _ SERVER ['php _ SELF'], "/") + 1 ); // why add 1? Because you need to exclude the previous/
A recommended function
// Obtain 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 the problem. in many cases, we need the help of some string truncation functions to get the desired results.
The above is the content of the PHP code sample for obtaining the name of the currently executed php file. For more information, see PHP Chinese network (www.php1.cn )!