This article mainly introduces the code for PHP to obtain the name of the currently executing PHP file. Friends who need it can refer to
This problem encountered in the navigation judgment when writing the confession wall today. My solution is as follows:
Determine the current php file name to determine which part of the navigation bar is highlighted.
How does php get the current url file name?
This is how I handle it:shock:
Tutorial
First of all, we must get the current page URL. Here we use php$ _SERVER['PHP_SELF']
To get the web page address
Assume the url is http://www.php.cn/
$php_Self= $_SERVER['PHP_SELF']; //获取网页地址 //输出结果:http://www.php.cn/
Output Later, we found that we only need index.php, and the previous list of things are useless.
How to do it?
Here we use the substr() function. substr()
is used to return part of the string:
substr syntax
substr(string,start,length)
Parameter | Description |
---|---|
string | Required. Specifies a part of the string to be returned. |
start | Required. Specifies where in the string to begin.
|
Optional. Specifies the length of the returned string. The default is until the end of the string.
|
So we need to use the
strrpos() function to get the position of the last occurrence.
strrpos syntax
strrpos(string,find,start)Description | |
---|---|
Required. Specifies the string to be searched for. | |
Required. Specifies the characters to search for. | |
Optional. Specifies where to start the search. |
$php_Self = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/")+1); //为啥要加1呢?因为要排除前面的那个 /
//获得当前的脚本网址 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; }