init.php file PHP summary of methods to obtain the parent directory of the current file

WBOY
Release: 2016-07-27 16:56:17
Original
1049 people have browsed it

Method 1: First get the length of the folder where the current file is located, and then use substr to intercept the length:

Copy the code The code is as follows:

$dirName = str_replace("\", "/", dirname (__FILE__));
$dirNameLength = strlen($dirName);
$currentDirNameLength = $dirNameLength - strrpos($dirName,"/"); //Get the length of the folder where the current file is located!
$parentDirName = substr($dirName,0,-$currentDirNameLength); //If the third parameter is a negative number, it means that [the absolute value of the parameter] characters will be intercepted from the back.

Method 2: Treat the folder where the current file is located as a file (the folder is actually a special file, everything is a file!!), just use dirname to nest the dirname once:

 $parentDirName = dirname(dirname(__FILE__));
Copy after login

From It can be seen from the above: a deep understanding of things can greatly improve the quality of the code!

Attached: PHP gets the path or directory implementation

PHP gets the directory and the method through magic variables; through super global variables; through related functions, etc.:

<&#63;php
/**
 * PHP获取路径或目录实现
 */
 
//魔术变量,获取当前文件的绝对路径
echo "__FILE__: ========> ".__FILE__; 
echo '<br/>';
 
//魔术变量,获取当前脚本的目录
echo "__DIR__: ========> ".__DIR__;
echo '<br/>';
 
//dirname返回路径的目录部分,dirname(__FILE__)相当于__DIR__
echo "dirname(__FILE__): ========> ".dirname(__FILE__);
echo '<br/>';
 
//$_SERVER['PHP_SELF']和$_SERVER['SCRIPT_NAME']的结果一般相同,他们都是获取当前脚本的文件名
//只有当php以cgi方式运行时有区别,但是现在几乎找不到以cgi方式运行php了
echo '$_SERVER["PHP_SELF"]: ========> '.$_SERVER['PHP_SELF'];
echo '<br/>';
 
echo '$_SERVER["SCRIPT_NAME"]: ========> '.$_SERVER['SCRIPT_NAME'];
echo '<br/>';
 
//当前执行脚本的绝对路径。记住,在CLI方式运行php是获取不到的
echo '$_SERVER["SCRIPT_FILENAME"]: ========> '.$_SERVER['SCRIPT_FILENAME'];
echo '<br/>';
 
//当前运行脚本所在的文档根目录。在服务器配置文件中定义。
echo '$_SERVER["DOCUMENT_ROOT"]: ========> '.$_SERVER['DOCUMENT_ROOT'];
echo '<br>';
 
//getcwd()返回当前工作目录
echo "getcwd(): ========> ".getcwd();
echo '<br>';
Copy after login

The above introduces the init.php file and a summary of PHP methods to obtain the parent directory of the current file, including the content of the init.php file. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!