Prev | Current Page 342 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


This section introduces many of PHP??™s built-in functions for obtaining these
important details.
Parsing Directory Paths
It??™s often useful to parse directory paths for various attributes such as the tailing
extension name, directory component, and base name. Several functions are available
for performing such tasks, all of which are introduced in this section.
Retrieving a Path??™s Filename
The basename() function returns the filename component of a path. Its prototype
follows:
string basename(string path [, string suffix])
CHAPTER 10 ?–  WORKING WITH T HE FILE A ND OPERATING SYSTEM 279
If the optional suffix parameter is supplied, that suffix will be omitted if the
returned file name contains that extension. An example follows:
$path = "/home/www/data/users.txt";
printf("Filename: %s
", basename($path));
printf("Filename sans extension: %s
", basename($path, ".txt"));
?>
Executing this example produces the following:
Filename: users.txt
Filename sans extension: users
Retrieving a Path??™s Directory
The dirname() function is essentially the counterpart to basename(), providing the
directory component of a path. Its prototype follows:
string dirname(string path)
The following code will retrieve the path leading up to the file name users.txt:
$path = "/home/www/data/users.txt";
printf("Directory path: %s", dirname($path));
?>
This returns the following:
Directory path: /home/www/data
Learning More About a Path
The pathinfo() function creates an associative array containing three components of
a path, namely the directory name, the base name, and the extension.


Pages:
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354