Method One: First obtain the length of the folder in which the current file is located, and then use substr to intercept the length:
Copy the Code code 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 3rd parameter is a negative number, then the "absolute value of this parameter" character is truncated from the back.
Method Two: The current file in the same folder as a file (folder is actually a special file, everything is a file!!) ), dirname can be nested directly with dirname:
$parentDirName = DirName (dirname (__file__));
From the above can be seen: the deep understanding of things, can greatly improve the code quality!
Attached: PHP Get path or directory implementation
PHP gets directories and methods through magic variables, through super global variables, through related functions and so on:
<?php/** * PHP Get path or directory implementation *///Magic variable, get the absolute path of the current file echo "__file__: ========>". __file__; Echo '
'; Magic variable, gets the directory of the current script echo "__dir__: ========>". __dir__;echo '
'; DirName returns the directory portion of the path, dirname (__file__) equals __dir__echo "DirName (__file__): ========>". dirname (__file__); Echo '
'; The results of $_server[' php_self ' and $_server[' script_name '] are generally the same, they all get the file name of the current script//Only when PHP is running in CGI mode, But now it's almost impossible to find a CGI run of PHP Echo ' $_server[' Php_self "]: ========> '. $_server[' php_self '];echo '
'; Echo ' $_server[' Script_name "]: ========> '. $_server[' script_name '];echo '
'; The absolute path of the current execution script. Remember that running PHP in the CLI mode is not getting the echo ' $_server[' Script_filename "]: ========> '. $_server[' script_filename '];echo '
'; The document root directory where the script is currently running. Defined in the server configuration file. Echo ' $_server[' Document_root "]: ========> '. $_server[' document_root '];echo '
'; GETCWD () returns the current working directory echo "GETCWD (): ========>". GETCWD (); Echo '
';
The above describes the init.php file PHP to get the current file of the parent directory method summary, including the contents of the init.php file, I hope to be interested in PHP tutorial friends helpful.