PHP is a widely-used backend development language offering many convenient built-in functions. Among them, the dirname() function is mainly used to get the directory name of a specified file path. This article provides a comprehensive overview of dirname() usage, its return values, and practical examples.
The dirname() function takes a file path as a parameter and returns the directory name of that path. It is commonly used together with PHP’s magic constant __FILE__ to get the directory of the current script file. For example:
<span class="fun">dirname(__FILE__);</span>
This function simplifies file path handling, making it easier for developers to dynamically retrieve a file’s directory.
When passing a directory path as the argument, dirname() returns its parent directory. For example:
<span class="fun">echo dirname('/usr/local/bin'); // Outputs /usr/local</span>
When the argument is a file path, dirname() returns the directory where the file resides:
<span class="fun">echo dirname('/usr/local/bin/php'); // Outputs /usr/local/bin</span>
If the parameter is the current directory "." or if the path does not exist, dirname() returns "." indicating the current directory:
echo dirname('.'); // Outputs .
echo dirname('/usr/local/bin/'); // Outputs /usr/local/bin
The following example shows how to get the directory of a configuration file using dirname(), and then read the config file:
[db]
host = localhost
user = root
password = 123456
dbname = test
PHP code:
$config_file = 'config.ini';
$config_dir = dirname(__FILE__) . '/' . $config_file;
if (!file_exists($config_dir)) {
exit("Configuration file does not exist!");
}
$config_array = parse_ini_file($config_dir);
if (!$config_array) {
exit("Failed to read configuration file!");
}
echo "Configuration file directory: " . dirname($config_dir);
This code first checks if the configuration file exists, exiting with an error message if it does not. If the file exists, it attempts to read it, exiting on failure. Finally, it outputs the directory of the configuration file.
dirname() is a very useful PHP function for easily obtaining the directory part of a file path. It is commonly used in scenarios such as configuration management and path handling. Mastering its usage can greatly improve code flexibility and robustness.