PHP Path and File Operations: Absolute/Relative Paths, Pathinfo, and Directory Functions

This article explains how to work with absolute and relative file paths in PHP, demonstrates extracting path components with pathinfo(), and provides practical examples of directory and file manipulation functions such as opendir, readdir, scandir, fopen, fread, fwrite, unlink, copy, and rename.

php Courses
php Courses
php Courses
PHP Path and File Operations: Absolute/Relative Paths, Pathinfo, and Directory Functions

This guide introduces the concepts of absolute and relative paths in PHP, showing how an absolute path starts from the drive letter (e.g., D:\Google\123\1.png) and a relative path is based on the current file's directory (e.g., ./1.txt or ../2.txt).

It then demonstrates the pathinfo() function, which returns an associative array containing dirname, basename, extension, and filename for a given path:

<?php
$xianyu = "/love/xianyu.php";
$result = pathinfo($xianyu);
foreach ($result as $key => $value) {
    echo "$key=>$value
";
}
?>
/*
dirname=>/love
basename=>xianyu.php
extension=>php
filename=>xianyu
*/

For quick retrieval of just the filename, basename() can be used:

<?php
$xianyu = "/love/xianyu.php";
echo "Filename is: " . basename($xianyu);
?>
/* Output: Filename is: xianyu.php */

Similarly, dirname() returns the directory part of a path:

<?php
$filepath = "/love/xianyu.php";
echo "Directory part is: " . dirname($filepath);
?>
/* Output: Directory part is: /love */

Directory handling functions are covered next. opendir() opens a directory and returns a handle, which must be closed with closedir():

<?php
$dir = "images";
if ($dir_handle = opendir($dir)) {
    echo "Directory handle obtained!";
    closedir($dir_handle); // release handle
} else {
    echo "Failed to open directory";
}
?>

Creating and deleting directories use mkdir() and rmdir() respectively:

<?php
mkdir("123");
?>
<?php
rmdir("123");
?>

Current working directory can be obtained with getcwd() and changed with chdir():

<?php
echo getcwd() . "<br>";
chdir('hhh');
echo getcwd() . "<br>";
?>

Reading directory entries can be done with readdir() (one entry per call) or scandir() (returns an array of entries, optionally sorted):

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        echo "$file
";
    }
    closedir($handle);
}
?>
<?php
$dir1 = scandir("D:\\NewFolder");
$dir2 = scandir("D:\\NewFolder", 1); // descending order
print_r($dir1);
print_r($dir2);
?>

File operations start with checking existence using file_exists():

<?php
if (file_exists("test.txt")) {
    // perform actions
}
?>

Opening, reading, and closing files can be performed with fopen(), fread(), and fclose(), or more simply with file_get_contents():

<?php
$filename = "test.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
// simpler
$contents = file_get_contents($filename);
?>

Writing to files uses fwrite() or file_put_contents():

<?php
$handle = fopen("test.txt", "w");
fwrite($handle, "Add text to file");
fclose($handle);
// simpler
file_put_contents("test.txt", "Content written with file_put_contents()");
?>

Additional file management functions include unlink() to delete a file, copy() to duplicate a file, and rename() to move or rename files or directories:

<?php
unlink("temp.txt");
?>
<?php
copy("html/cache.txt", "html/copyCache.txt");
?>
<?php
rename('test.txt', 'rename.txt'); // rename file
rename('test', 'rename'); // rename directory
rename('test.txt', 'test/a.txt'); // move and rename file
rename('test', 'html/test'); // move directory
?>

Overall, the article provides a comprehensive reference for handling paths, extracting path components, and performing common directory and file operations in PHP.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendfile systempathphp-functionsdirectory
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.