Broad Network


Directories in PHP

Files and Directories with Security Considerations in PHP - Part 4

Foreword: In this part of the series, I explain how to work with directories in PHP.

By: Chrysanthus Date Published: 19 Jan 2019

Introduction

This is part 4 of my series, Files and Directories with Security Considerations in PHP. In this part of the series, I explain how to work with directories in PHP. You should have read the previous parts of the series before reaching here, as this is the continuation.

Working Directory
The working directory is the directory that has your PHP script. It is represented by a dot or its name with path. The parent directory is identified by two dots or its name with path. Use your operating system to create the directories of the following directory path:

    C:/dir1/dir2/dir3

Assume that your PHP script is in the dir2 subdirectory. To execute your script at the console, you would type:

    chdir C:/dir1/dir2

and press Enter, to go to the directory first.

chdir
To change directory in PHP, there is a function called, chdir. This function returns true on success and false on failure. If you type:

    chdir(".");

in your PHP code, chdir will lead you to your current directory, which in this case, causes no change because the PHP script is in the current directory. Note that the dot is in quotes. To go to the parent directory, you would type:

    chdir("..");

To go to any directory, anywhere in the disk, use the path of the directory. To go to dir3 from any directory in the disk, you would type:

  chdir("c:/dir1/dir2/dir3");

For the directories in the path, there should be no space in the name.

getcwd
To obtain the name of the current working directory, use the function whose syntax is:

    string getcwd ()

Try the following code:

<?php

    chdir("c:/dir1/dir2/dir3");

    $str = getcwd ();

    echo $str;

?>

The output should be:

    C:/dir1/dir2/dir3

mkdir
This is the function to create a directory. You can create a subdirectory to the working directory. The following statement creates dir4 in dir3, while the working directory is dir2:

    mkdir("dir3/dir4");

You create only one directory at a time. So, to create a directory, folder1 in the directory, temp that already exists in the root directory, type:

    mkdir("c:/temp/folder1");

rmdir
This is the function to delete (remove) a directory. In order for the directory to be removed, it must be empty (delete all its content first). Only one directory is removed at a time. The following statement removes dir4, while the working directory is dir2.

    rmdir("dir3/dir4");

Listing all the files and Immediate Subdirectories of a Directory
The following code will copy the names of all the files into the array, one filename to an array cell.

<?php

    $arr = glob("*.*");

    foreach ($arr as $item)
        {
            echo $item, '<br>';
        }

?>

glob("*.*") does not copy the directory names. If you want to copy the filenames and directory names, use glob("*") as follows:

    $arr = glob("*");

Note the use of "*.*" for files only; and the use of "*" for files and directories.

chroot
This function makes the named directory the new root directory for all further pathnames that begin with a / by your program (and all its children). It does not make the new directory the working directory (working directory stays the same). Consider the following path:

    c:/dirA/dirB/dirC/dirD

Now, c:/ is the root directory. In PHP you can access the root directory by simply typing /.

You can make any directory the root directory, so that its subdirectories can be accessed beginning with /. To make dirB the root directory, you would type:

    chroot("c:/dirA/dirB");

From that you can then go on to type,

    $arr = glob("/dirC/*");

and all the file names and directory names in dirC will be copied to the array.

opendir, readdir, rewinddir, closedir
You can open the content of a directory and manipulate it in a similar way that you would open and manipulate the content of a file. The following code displays five items (directories and/or files) of the current directory with the first item displayed twice:

<?php

    if (!$handle = opendir('.'))
        echo "Cannot open directory";

        echo readdir($handle), '<br>';
        echo readdir($handle), '<br>';
        echo readdir($handle), '<br>';
        echo readdir($handle), '<br>';
        echo readdir($handle), '<br>';

        rewinddir($handle);

        echo readdir($handle), '<br>';

        closedir($handle);

?>

I tried the code and I had:

    .
    ..
    agreement.htm
    apachehaus.ico
    approveCom.php
    .

Only the current and parent directories were displayed. No other directory was displayed. All files would be displayed.

Security Considerations

chdir()
bool chdir ( string $directory )

Changes PHP's current directory to $directory.

Returns TRUE on success or FALSE on failure.

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

getcwd()
string getcwd ( void )

Gets the current working directory.

Note: On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does.

mkdir()
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] )

Attempts to create the directory specified by pathname.

Returns TRUE on success or FALSE on failure.

Note: mode is ignored on Windows.

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

rmdir()
bool rmdir ( string $dirname [, resource $context ] )

Attempts to remove the directory named by dirname. The directory must be empty, and the relevant permissions must permit this. A E_WARNING level error will be generated on failure.

Returns TRUE on success or FALSE on failure.

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

chroot()
bool chroot ( string $directory )

Changes the root directory of the current process to directory, and changes the current working directory to "/".

Returns TRUE on success or FALSE on failure.

Note: This function is not implemented on Windows platforms.

opendir()
resource opendir ( string $path [, resource $context ] )

Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls.

Returns a directory handle resource on success, or FALSE on failure.

Note: If path is not a valid directory or the directory can not be opened due to permission restrictions or filesystem errors, opendir() returns FALSE and generates a PHP error of level E_WARNING. You can suppress the error output of opendir() by prepending '@' to the front of the function name.

rewinddir()
void rewinddir ([ resource $dir_handle ] )

Resets the directory stream indicated by dir_handle to the beginning of the directory.

Returns NULL on success or FALSE on failure.

closedir()
void closedir ([ resource $dir_handle ] )

Closes the directory stream indicated by dir_handle. The stream must have previously been opened by opendir().

dir_handle
    The directory handle resource previously opened with opendir(). If the directory handle is not specified, the last link opened by opendir() is assumed.

As of now, void means, returns null.

scandir()
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )

directory
    The directory that will be scanned.

sorting_order
    By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is set to SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in descending order. If it is set to SCANDIR_SORT_NONE then the result is unsorted.

Returns an array of filenames on success, or FALSE on failure. If directory is not a directory, then boolean FALSE is returned, and an error of level E_WARNING is generated.

Time to take a break. Let us stop here and continue in the next part.

Chrys


Related Links

Basics of PHP with Security Considerations
White Space in PHP
PHP Data Types with Security Considerations
PHP Variables with Security Considerations
PHP Operators with Security Considerations
PHP Control Structures with Security Considerations
PHP String with Security Considerations
PHP Arrays with Security Considerations
PHP Functions with Security Considerations
PHP Return Statement
Exception Handling in PHP
Variable Scope in PHP
Constant in PHP
PHP Classes and Objects
Reference in PHP
PHP Regular Expressions with Security Considerations
Date and Time in PHP with Security Considerations
Files and Directories with Security Considerations in PHP
Writing a PHP Command Line Tool
PHP Core Number Basics and Testing
Validating Input in PHP
PHP Eval Function and Security Risks
PHP Multi-Dimensional Array with Security Consideration
Mathematics Functions for Everybody in PHP
PHP Cheat Sheet and Prevention Explained
More Related Links

Cousins

BACK NEXT

Comments