Broad Network


PHP Filehandle and File Name

Files and Directories with Security Considerations in PHP - Part 3

Foreword: In this part of the series, I talk about PHP File Resource and File Name. I also explain how to delete, rename, copy and move a file.

By: Chrysanthus Date Published: 19 Jan 2019

Introduction

This is part 3 of my series, Files and Directories with Security Considerations in PHP. In this part of the series, I talk about PHP File Resource and File Name. I also explain how to delete, rename, copy and move a file. You should have read the previous parts of the series before reaching here, as this is the continuation.

Renaming a File
You can change the name of a file, say from myFile.txt to input.txt . The file should not be opened before you rename it. You use the rename() function. The syntax is:

    bool rename ( string $oldname , string $newname [, resource $context ] )

Attempts to rename oldname to newname, moving it between directories if necessary. If renaming a file and newname exists, it will be overwritten. If renaming a directory and newname exists, this function will emit a warning.

Returns TRUE on success or FALSE on failure.

A simple function call is:

    rename("myFile.txt", "input.txt");

Deleting a File
To delete a file, you use the unlink() function. The syntax is:

    bool unlink ( string $filename [, resource $context ] )

Deletes filename. An E_WARNING level error will be generated on failure.

Returns TRUE on success or FALSE on failure.

A simple function call is:

    unlink('temp3.txt');

You can precede the filename (proper) with the directory path.

Expanding Filenames Using Wildcards
Imagine that you have files in a directory, which have the .doc extension. You can copy the actual names of all these files to an array, as follows:

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

Note that the glob function has one argument, which is a string. Note the use of the wildcard character, * in the pattern. The following code displays the actual filenames in the array for files, "*.txt":

<?php

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

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

?>

I tried it in my computer and I had:

    temp.txt
    temp1.txt
    temp2.txt

The syntax of the glob function is:

array glob ( string $pattern [, int $flags = 0 ] )

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

pattern
        The pattern. No tilde expansion or parameter substitution is done.
Valid flags:
        GLOB_MARK - Adds a slash to each directory returned
        GLOB_NOSORT - Return files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically
        GLOB_NOCHECK - Return the search pattern if no files matching it were found
        GLOB_NOESCAPE - Backslashes do not quote metacharacters
        GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'
        GLOB_ONLYDIR - Return only directory entries which match the pattern
        GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored.

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Note: On some systems it is impossible to distinguish between empty match and an error.
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
Note: This function isn't available on some systems (e.g. old Sun OS).
Note: The GLOB_BRACE flag is not available on some non GNU systems, like Solaris.

Copying a File
The following code will copy the file, afile.txt from the directory, c:/dir1/dir2 to the directory c:/dirA/dirB.

<?php

    if (!$in = fopen('c:/dir1/dir2/afile.txt', 'r')) echo "Cannot open file.";
    if (!$out = fopen('c:/dirA/dirB/afile.txt', 'w')) echo "Cannot open file.";

    while (($char = fgetc($in)) !== false)
        {
            if (fputs($out, $char) === false)
                {
                    echo "Cannot write byte.";
                }
        }

    fclose($in);
    fclose($out);

?>

Note the use of the modes, 'r' and 'w'. The reading and writing is done, byte-by-byte.

Moving Files
To move a file, you copy the file first and then you delete the source file. So if the above file was to be moved, you will just have to add the following code segment at the bottom of the script:

    $boo = unlink("C:/dirA/dirB/afile.txt");

    if (!$boo)
        {
            print "Source file could not be deleted.";
        }

Printing to more than one File in One Sweep
Read and test the following code:

<?php

    if (!$arr[] = fopen('output1.txt', 'w')) echo "Cannot open file";
    if (!$arr[] = fopen('output2.txt', 'w')) echo "Cannot open file";
    if (!$arr[] = fopen('output3.txt', 'w')) echo "Cannot open file";

    foreach ($arr as $handle) fwrite($handle, "I love you.");

    foreach ($arr as $handle) fclose($handle);
            
    echo 'All data written';

?>

File Test
You can test whether a file is empty; you can test whether a file even exist; you can test other issues for a file.

The file_exists() Function

    bool file_exists ( string $filename )

Checks whether a file or directory exists.

filename
    Path to the file or directory.

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

Note: This function will return FALSE for symlinks pointing to non-existing files.

Warning: This function returns FALSE for files inaccessible due to safe mode restrictions. However these files still can be included if they are located in safe_mode_include_dir.

Note: The check is done using the real UID/GID instead of the effective one.
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Notes: The results of this function are cached.

The filesize() Function

    int filesize ( string $filename )

Gets the size for the given file.

filename
    Path to the file.

Returns the size of the file in bytes, or FALSE (and generates an error of level E_WARNING) in case of an error.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
Note: The results of this function are cached.

The is_dir() Function

    bool is_dir ( string $filename )

Tells whether the given filename is a directory.

filename
    Path to the file. If filename is a relative filename, it will be checked relative to the current working directory. If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled safe mode, or open_basedir further restrictions may apply.

Returns TRUE if the filename exists and is a directory, FALSE otherwise.

Note: The results of this function are cached.

The is_file() Function

    bool is_file ( string $filename )

Tells whether the given file is a regular file.

filename
    Path to the file.

Returns TRUE if the filename exists and is a regular file, FALSE otherwise.

Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.

Note: The results of this function are cached.

The is_link() Function

    bool is_link ( string $filename )

Tells whether the given file is a symbolic link.

filename
    Path to the file.

Returns TRUE if the filename exists and is a symbolic link, FALSE otherwise.

Note: The results of this function are cached.


Try the following code, which returns the file size in bytes.

<?php

    $size = filesize('temp2.txt');

    echo $size;

?>

I tried the code and I had, 6 for the size.

That is it for this part of the series. We 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