Category: File Handling

  • Read File

    What is File Reading?

    Working with online applications frequently needs reading data from files. PHP makes it easy to read files from your server. File reading is the process of opening a file and extracting its data for usage in your program. For example, you may want to read a text file that contains user information, configuration settings or product specifications.

    How to Read a File in PHP?

    There are a number of options in PHP for reading data from a file that has been opened with the fopen() function. The following built-in functions in PHP’s library can help us perform the read operation −

    • file_get_contents() − reads a file into a string.
    • fgets() − gets a line from the file pointer.
    • fgetc() − returns a string with a single character from the file pointer.
    • fread() − reads a specified number of bytes from the file pointer.
    • fscanf() − reads data from the file and parses it as per the specified format.

    Using file_get_contents() Function

    This function reads the entire file into a string. It is the simplest way to read a file.

    file_get_contents($path,$include_path,$context,$start,$max_length)

    Example

    The following code reads the entire available content from the “myfile.txt” file −

    <?php
       // Specify the path to the file
       $filename = 'myfile.txt';
    
       // Read the content of the file
       $content = file_get_contents($filename);
    
       // Check if the file was read successfully
       if ($content === false) {
    
      echo "Error reading the file.";
    } else {
      echo "File content: " . $content;
    } ?>

    Output

    It will produce the following output −

    File content: Hello this is an example of 
    PHP read file.
    
    This is a new line in the file.
    

    Using fgets() Function

    The fgets() function can return a line from an open file. This function stops returning on a new line at a specified length or EOF, whichever comes first and returns false on failure.

    fgets(resource$stream,?int$length=null):string|false

    Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with read or read/write mode, and $length is an optional parameter specifying the number of bytes to be read.

    The read operation ends when “length-1” bytes are read or a newline is encountered, whichever is first.

    Example

    The following code reads the first available line from the “hello.txt” file −

    <?php
       $file = fopen("hello.txt", "r");
       $str = fgets($file);
       echo $str;
       fclose($file);
    ?>

    Output

    It will produce the following output −

    Hello World
    

    Example

    You can put the fgets() function in a loop to read the file until the end of file is reached.

    <?php
       $file = fopen("hello.txt", "r");
       while(! feof($file)) {
    
      echo fgets($file). "&lt;br&gt;";
    } fclose($file); ?>

    Output

    It will produce the following output −

    Hello World
    TutorialsPoint
    PHP Tutorials
    

    Here, we have used the feof() function which returns true if the file pointer is at EOF; otherwise returns false.

    Using fgetc() Function

    The fgetc() function returns a single character read from the current position of the file handle. It returns false when EOF is encountered.

    fgetc(resource$stream):string|false

    Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with read or read/write mode.

    Example

    The following code displays the first character read from the “hello.txt” file −

    <?php
       $file = fopen("hello.txt", "r");
       $str = fgets($file);
       echo $str;
       fclose($file);
    ?>

    Output

    It will produce the following output −

    H
    

    Example

    You can also put the fgetc() function inside a loop to read the file character by character until it reaches EOF.

    <?php
       $file = fopen("hello.txt", "r");
       while(! feof($file)) {
    
      $char = fgetc($file);
      if ($char == "\n")
      echo "&lt;br&gt;";
      echo $char;
    } fclose($file); ?>

    Output

    It will produce the following output −

    Hello World
    TutorialsPoint
    PHP Tutorials
    

    Using fread() Function

    The fread() function in PHP is a binary-safe function for reading data from a file. While the fgets() function reads only from a text file, the fread() function can read a file in binary mode.

    fread(resource$stream,int$length):string|false

    Here, the $stream parameter is a file pointer or handle to the file opened with the fopen() function with binary read or read/write mode (rb or rb+). The $length parameter specifies number of bytes to be read.

    If the $length parameter is not given, PHP tries to read the entire file until EOF is reached, subject to the chunk size specified.

    Example

    The following code reads a text file −

    <?php
       $name = "hello.txt";
       $file = fopen($name, "r");
       $data = fread($file, filesize($name));
       echo $data;
       fclose($file);
    ?>

    Output

    It will produce the following output −

    Hello World TutorialsPoint PHP Tutorials
    

    Example

    You can also read a non-ASCII file such as an image file opened in rb mode.

    <?php
       $name = "welcome.png";
       $file = fopen($name, "rb");
       $data = fread($file, filesize($name));
       var_dump($data);
       fclose($file);
    ?>

    The browser displays the “var_dump” information as the following −

    PHP Read File

    Using fscanf() Function

    The fscanf() function in PHP reads the input from a file stream and parses it according to the specified format, thereby converts it into the variables of respective types. Each call to the function reads one line from the file.

    fscanf(resource$stream,string$format,mixed&...$vars):array|int|false|null

    Here, the $stream parameter is the handle to the file opened with the fopen() function and in read mode. And, $format is a string containing one or more of the following formatting specifiers −

    • %% − Returns a percent
    • %b − Binary number
    • %c − The character according to the ASCII value
    • %f − Floating-point number
    • %F − Floating-point number
    • %o − Octal number
    • %s − String
    • %d − Signed decimal number
    • %e − Scientific notation
    • %u − Unsigned decimal number
    • %x − Hexadecimal number for lowercase letters
    • %X − Hexadecimal number for uppercase letters

    $vars is an optional parameter that specifies variables by reference which will contain the parsed values.

    Assuming that the “employees.txt” file is available in the same directory in which the PHP script given below is present. Each line in the text file has name, email, post and salary of each employee, separated by tab character.

    Example

    The following PHP script reads the file using the format specifiers in fscanf() function −

    <?php
       $fp = fopen("employees.txt", "r");
       while ($employee_info = fscanf($fp, "%s\t%s\t%s\t%d\n")) {
    
      list ($name, $email, $post, $salary) = $employee_info;
      echo "&lt;b&gt;Name&lt;/b&gt;: $name &lt;b&gt;Email&lt;/b&gt;: 
    $email <b>Salary</b>: Rs. $salary <br>"; } fclose($fp); ?>

    Output

    It will produce the following output −

    Name: Ravishankar Email: [email protected] Salary: Rs. 40000
    Name: Kavita Email: [email protected] Salary: Rs. 25000
    Name: Nandkumar Email: [email protected] Salary: Rs. 30000
  • Open File

    When working with PHP, you will need to read and write files. This chapter explains how to open a file in PHP. This is a important skill for any web developer who want to manage data properly.

    PHP’s built-in function library provides fopen() function to open a file or any other stream and returns its “reference pointer”, also called as “handle”.

    The fopen() function in PHP is similar to fopen() in C, except that in C, it cannot open a URL.

    Why Do We Need to Open Files?

    Opening files allows you to −

    • Retrieve data (like user submissions).
    • Save data (like user-generated content).
    • Handle various types of file formats (like JSON, CSV, and XML).

    How to Open a File in PHP

    To open a file with PHP, use the fopen() function. This function needs two parameters −

    • The name of the file.
    • The mode in which you want to open the file.

    Syntax of fopen()

    The fopen() function has the following signature −

    fopen(string$filename,string$mode,bool$use_include_path=false,?resource$context=null):resource|false

    Parameters

    The $filename and $mode parameters are mandatory. Here’s the explanation of the parameters −

    • $filename − This parameter is a string representing the resource to be opened. It may be a file in the local filesystem, or on a remote server with the scheme:// prefix.
    • $mode − A string that represents the type of access given to the file/resource.
    • $use_include_path − A Boolean optional parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.
    • $context − A context stream resource.

    Modes of Opening a File

    PHP allows a file to be opened in the following modes −

    ModesDescription
    rOpen a file for read only.
    wOpen a file for write only. creates a new file even if it exists.
    aOpen a file in append mode
    xCreates a new file for write only.
    r+Open a file for read/write.
    w+Open a file for read/write. creates a new file even if it exists.
    a+Open a file for read/write in append mode.
    x+Creates a new file for read/write.
    cOpen the file for writing, if it doesn’t exist. However, if it exists, it isn’t truncated (as in w mode).
    c++Open the file for read/write, if it doesn’t exist. However, if it exists, it isn’t truncated (as in w mode).
    eSet close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

    If the fopen() function is successfully executed, it returns a “file pointer” or “handle” resource bound to the file stream. However, if it fails, it returns false with E_WARNING being emitted.

    $handle=fopen('a.txt, 'r');var_dump($handle);

    If the file exists in the current directory, the success is shown by the output −

    resource(5) of type (stream)
    

    If not, you get the following error message −

    Warning: fopen(a.txt): Failed to open stream: 
    No such file or directory in a.php on line 2
    bool(false)
    

    Examples

    The following examples show different usages of the fopen() function −

    <?php
       // Opening a file for writing   
       $handle = fopen("hello.txt", "w");
    
       $handle = fopen("c:/xampp/htdocs/welcome.png", "rb");
    
       // Opening a file for reading
       $handle = fopen("http://localhost/hello.txt", "r");
    ?>

    Note that this function may also succeed when the filename is a directory. In that case, you may need to use the is_dir() function to check whether it is a file before doing any read/write operations.

    Once a file is opened, you can write data in it with the help of functions such as fwrite() or fputs(), and read data from it with fread() and fgets() functions.

    Closing a File

    It is always recommended to close the open stream referenced by the handle −

    fclose($handle);

    Important Notes

    Here are some important point you need to keep in mind while working with file Handling −

    • Always make sure the file opened successfully. It is a good idea to verify that the file opened successfully. If it did not, you can accept the error carefully.
    • When you are finished reading or writing, always use fclose() to close your file. This releases system resources.
  • File Handling

    In PHP, a file is a resource object, from which data can be read or written to in a linear fashion. The term “file handling” refers to a set of functions in PHP that enable read/write operations on disk files with PHP code.

    A file object is classified as a stream. Any resource on which linear read/write operations are done is a stream. Other stream-like objects are the TCP sockets, standard input stream, i.e., a system keyboard represented by “php://stdin”, the standard output stream represented by “php://stdout”, and the error stream “php://stderr”.

    Note − The constants STDIN, STDOUT, and STDERR stand for the respective standard streams.

    Although PHP is regarded as a server-side scripting language for developing web applications, PHP also has a command-line interface to perform console IO operations.

    What is File Handling?

    File handling refers to the process of managing files on a server. In PHP, this includes −

    • Open a file.
    • Reading data from a file.
    • Writing data into a file.
    • Close the file.

    Why Use File Handling?

    File handling is important since it allows you to −

    • Store user information.
    • Manage logs.
    • Create configuration files.
    • Generate reports.

    Now, let us look at how to manage files in PHP.

    Opening a File

    To open a file in PHP, we use the fopen() function. This function requires two parameters: the path to the file and the mode (what you want to do with the file).

    Here are some common modes you might use −

    • “r”: Read only.
    • “w”: Write only (truncates the file to zero length).
    • “a”: Write only (append).
    • “r+”: Read and write.

    Example: Opening a File

    Here is the example showing how you can open a file using the PHP file handling −

    // Opens the file for reading$file=fopen("/PHP/PhpProjects/myfile.txt","r");if($file){echo"File opened successfully!";}else{echo"Error opening the file.";}

    Output

    Here is the outcome of the following code −

    File opened successfully!
    

    Reading from a File

    When you have opened a file then you can read its contents with the help of ‘fgets() or fread()’.

    • fgets($file): Reads a single line from the file.
    • fread($file, $length): Reads a specified number of bytes.

    Example: Reading a File

    Here is the example showing how you can read a file after opening it in PHP.

    <?php
       $file = fopen("/PHP/PhpProjects/myfile.txt", "r");
    
       while (($line = fgets($file)) !== false) {
    
      // Prints each line
      echo $line . "\n"; 
    } fclose($file); ?>

    Output

    This will create the below output −

    Hello this is an example of 
    
    PHP File Handling.
    

    Writing to a File

    To write data to a file you will have to open it in write mode (“w” or “a”). Then you can use ‘fwrite()’.

    Example: Writing to a File

    Here is the example showing how you can write content in a file −

    <?php
       // Opens the file for appending
       $file = fopen("/PHP/PhpProjects/myfile.txt", "a");
    
       if ($file) {
    
      // Write a line
      fwrite($file, "\nThis is a new line in the file.\n"); 
      
      // Close the file
      fclose($file); 
      echo "Data written to the file successfully!";
    } else {
      echo "Error opening the file.";
    } ?>

    Output

    Here is the output of the above code −

    Data written to the file successfully!
    

    Here is the updated content of the file myfile.txt −

    Hello this is an example of 
    
    PHP File Handling.
    
    This is a new line in the file.
    

    Closing a File

    When you are finished reading or writing to a file, use the fclose() method to properly close it. This helps free up system resources.

    Example: Closing a File

    Below is the example showing how you can use the fclose() function to close the opened file −

    <?php
       $file = fopen("/PHP/PhpProjects/myfile.txt", "r");
       // Do something with the file
       // Close the file
       fclose($file); 
    
       echo "The file has been closed.";
    ?>

    Output

    This will generate the below output −

    The file has been closed.
    

    File Handling Errors

    It is very important to handle errors when you are working with files. Use conditional statements to check if the file was opened successfully.

    Example: Error Handling

    You can follow the below example to handle errors while working with file handling −

    <?php
       $file = fopen("nonexistent.txt", "r");
       if (!$file) {
    
      echo "Error: File does not exist.";
    } else {
      // Read the file
      fclose($file);
    } ?>

    Output

    It will produce the following output −

    Error: File does not exist.
    

    Example: Get List of Stream Wrappers

    PHP supports a variety of stream protocols for stream related functions such as fopen(), file_exists(), etc. Use php_get_wrappers() function to get a list of all the registered wrappers.

    <?php
       print_r(stream_get_wrappers());
    ?>

    Output

    It will generate the following output −

    Array
    (
       [0] => php
       [1] => file
       [2] => glob
       [3] => data
       [4] => http
       [5] => ftp
       [6] => zip
       [7] => compress.zlib
       [8] => compress.bzip2
       [9] => https
       [10] => ftps
       [11] => phar
    )
    

    The streams are referenced as “scheme://target”. For instance, the file stream is “file://xyz.txt”.

    The input data from the console is stored in the computer’s main memory (RAM) until the application is running. Thereafter, the memory contents from RAM are erased.

    We would like to store it in such a way that it can be retrieved whenever required in a persistent medium such as a disk file. Hence, instead of the standard streams (keyboard for input and the display device for output), we will use the disk files for reading the data, and destination for storing the data.

    In addition to the read and write modes as used in the above example (IO operations with standard streams), the file stream can be opened in various other modes like “r+” and “w+” for simultaneous read/write, “b” for binary mode, etc.

    To open a disk file for reading and obtain its reference pointer, use the fopen() function.

    $handle=fopen('file://'.__DIR__.'/data.txt','r');

    The “file://” scheme is the default. Hence, it can be easily dropped, especially when dealing with local files.

    Note − It is always recommended to close the stream that was opened. Use the fclose() function for this purpose.

    fclose($handle);

    PHP has several built-in functions for performing read/write operations on the file stream. In the subsequent chapters, we shall explore the filesystem functions.