Home > Article > Backend Development > Differences and examples of dirname, basename, pathinfo functions in php
To get the path, directory or file name of a file in php, we often use dirname(), basename(), pathinfo() These three functions have been introduced separately in the previous article. This article mainly introduces to you in detail
The differences and usage examples of these three functions.
dirname() function
string dirname ( string $path )
php dirname function gets the directory part of the given file path , the parameter $path is a string of file paths
dirname() function is often used with the magic variable __FILE__, which represents the full path and file name of the currently running file.
dirname(dirname(__FILE__)); What you get is the name of the directory above the file
dirname(__FILE__); What you get is the name of the directory where the file is located
For example:
<?php echo dirname("c:/testweb/home.php")."<br/>"; echo dirname("/testweb/home.php")."<br/><br/>"; echo __FILE__ ."<br/>"; echo dirname(__FILE__)."<br/>"; echo dirname(dirname(__FILE__)); ?>
Code running result:
##basename() function
string basename ( string $path [, string $suffix ] )php The basename() function gets the file name part of the path, which is the opposite of dirname() (dirname gets the directory part of the path). The first parameter $path represents a string containing the full path to a file, and the second parameter represents that if the file name ends with suffix, this part will also be removed.
The example is as follows:
<?php var_dump(basename("/etc/sudoers.d", ".d")); var_dump(basename("/etc/passwd")); var_dump(basename("/etc/")); var_dump(basename(".")); var_dump(basename("/")); ?>
Code running result:
pathinfo() function
php The pathinfo function is used to parse the path and parse the path into an array. The array includes the directory name, complete file name, file extension and file name (excluding the file suffix), and the key names of these four values are dirname, basename, extension and filename respectively. We can use these four key names to obtain the values of the directory name, complete file name, file extension and file name. Syntax:mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )
Parameters: path The path to parse. options If specified, the specified elements will be returned; they include: PATHINFO_DIRNAME, PATHINFO_BASENAME and PATHINFO_EXTENSION or PATHINFO_FILENAME. If options are not specified, the default is to return all units.
Example:
<? $test = pathinfo("http://localhost/index.php"); print_r($test); ?>
Code running result:
The above is the detailed content of Differences and examples of dirname, basename, pathinfo functions in php. For more information, please follow other related articles on the PHP Chinese website!