Quick Contact

    Saving data for later using File system
    File System

    The filesystem functions allow you to access and manipulate the filesystem.

    The filesystem functions are part of the PHP core. There is no installation needed to use these functions.

    Unix / Windows Compatibility

    When specifying a path on Unix platforms, a forward slash (/) is used as directory separator.

    On Windows platforms, both forward slash (/) and backslash (\) can be used.

    Runtime Configuration

    The behavior of the filesystem functions is affected by settings in php.ini.

    Filesystem configuration options:

    Name Default Description Changeable
    allow_url_fopen “1” Allows fopen()-type functions to work with URLs (available since PHP 4.0.4) PHP_INI_SYSTEM
    user_agent NULL Defines the user agent for PHP to send (available since PHP 4.3) PHP_INI_ALL
    default_socket_timeout “60” Sets the default timeout, in seconds, for socket based streams (available since PHP 4.3) PHP_INI_ALL
    from “” Defines the anonymous FTP password (your email address) PHP_INI_ALL
    auto_detect_line_endings “0” When set to “1”, PHP will examine the data read by fgets() and file() to see if it is using Unix, MS-Dos or Mac line-ending characters (available since PHP 4.3)  
    Opening a file
    PHP Open File – fopen()

    A better method to open files is with the fopen() function. This function gives you more options than the readfile() function.

    We will use the text file, webdictionary.txt, during the lessons:

    AJAX = Asynchronous JavaScript and XML
    CSS = Cascading Style Sheets
    HTML = Hyper Text Markup Language
    PHP = PHP Hypertext Preprocessor
    SQL = Structured Query Language
    SVG = Scalable Vector Graphics
    XML = EXtensible Markup Language
    

    The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the specified file:

    Example

    <?php
    $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
    echo fread($myfile,filesize("webdictionary.txt"));
    fclose($myfile);
    ?>
    

    The file may be opened in one of the following modes:

    Modes Description
    r Open a file for read only. File pointer starts at the beginning of the file
    w Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file
    a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist
    x Creates a new file for write only. Returns FALSE and an error if file already exists
    r+ Open a file for read/write. File pointer starts at the beginning of the file
    w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file
    a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist
    x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
    Creating and Writing to a file
    Create File – fopen()

    The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.

    If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

    The example below creates a new file called testfile.txt. The file will be created in the same directory where the PHP code resides:

    Example

    $myfile = fopen("testfile.txt", "w")
    File Permissions

    If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.

    Write to File – fwrite()

    The fwrite() function is used to write to a file.

    The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.

    The example below writes a couple of names into a new file called newfile.txt:

    Example

    <?php
    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
    $txt = "John Doe\n";
    fwrite($myfile, $txt);
    $txt = "Jane Doe\n";
    fwrite($myfile, $txt);
    fclose($myfile);
    ?>
    

    Notice that we wrote to the file newfile.txt twice. Each time we wrote to the file we sent the string $txt that first contained John Doe and second contained Jane Doe. After we finished writing, we closed the file using the fclose() function.

    If we open the newfile.txt file it would look like this:

    John Doe
    Jane Doe
    
    PHP Overwriting

    Now that newfile.txt contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.

    In the example below we open our existing file newfile.txt, and write some new data into it:

    Example

    <?php
    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
    $txt = "Mickey Mouse\n";
    fwrite($myfile, $txt);
    $txt = "Minnie Mouse\n";
    fwrite($myfile, $txt);
    fclose($myfile);
    ?>
    

    If we now open the newfile.txt file, both John and Jane have vanished, and only the data we just wrote is present:

    Mickey Mouse
    Minnie Mouse
    
    Closing a file
    Close File – fclose()

    The fclose() function is used to close an open file.

    The fclose() requires the name of the file (or a variable that holds the filename) we want to close:

    <?php
    $myfile = fopen("webdictionary.txt", "r");
    // some code to be executed....
    fclose($myfile);
    ?>
    
    Reading from le
    Read File – fread()

    The fread() function reads from an open file.

    The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.

    The following PHP code reads the webdictionary.txt file to the end:

    fread($myfile,filesize("webdictionary.txt"));
    Deleting a file
    Delete() Function

    The delete() function deletes a file.

    This function returns TRUE on success and FALSE on failure.

    Syntax

    delete(file)

    Example

    <?php
    echo delete("target.txt");
    ?>
    

    The output of the code above will be:

    1
    Using other useful file functions
    Create a directory
    The mkdir() function creates a directory.

    This function returns TRUE on success, or FALSE on failure.

    Syntax

    mkdir(path,mode,recursive,context)
    Parameter Description
    path Required. Specifies the name of the directory to create
    mode

    Optional. Specifies permissions. By default, the mode is 0777 (widest possible access).

    The mode parameter consists of four numbers:

    • The first number is always zero
    • The second number specifies permissions for the owner
    • The third number specifies permissions for the owner’s user group
    • The fourth number specifies permissions for everybody else

    Possible values (to set multiple permissions, add up the following numbers):

    • 1 = execute permissions
    • 2 = write permissions
    • 4 = read permissions
    recursive Optional. Specifies if the recursive mode is set (added in PHP 5)
    context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream (added in PHP 5)

    Example

    <?php
    mkdir("testing");
    ?>
    
    Remove a directory

    The rmdir() function removes an empty directory.

    This function returns TRUE on success, or FALSE on failure.

    Syntax

    rmdir(dir,context)
    Parameter Description
    dir Required. Specifies the directory to be removed
    context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

    Example

    <?php
    $path = "images";
    if(!rmdir($path))
      {
      echo ("Could not remove $path");
      }
    ?>
    
    Summary

    The points summarizes the topic above:

    • The filesystem functions allow you to access and manipulate the filesystem.
    • PHP provides you all the possible functions you may need to manipulate a file.
    • The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.
    • If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

    Enrolled Yourself – PHP Training

    Copyright 1999- Ducat Creative, All rights reserved.