PHP 7 File Handling

PHP file handling functions allow us to store, access and manipulate the file.

These are the basic operations perform on a file.
  • Creating a file
  • Opening a file
  • Reading a file
  • Writing to a file
  • Closing a file

1. Creating a file -

PHP predefined function touch() is used to create a file.

Syntax - touch('filename');

Example -

<?php
    touch('text.txt'); // create a text file.
?>

2. Opening a file -

PHP predefined function fopen() is used to open a file from a local machine or a server or from a url.

Syntax - fopen('filename', 'mode')

Example -

<?php
    $file = fopen('text.txt', r);
?>

The above statement opens a file for reading purpose. The first parameter is a file name and the second parameter is accessed modifier which tells the purpose of opening a file, like read, write etc.

Six access modifiers of file -

r -> open the file for reading.
r+ -> open the file for reading and writing.
w -> open the file for writing, if no file exists with that name then it will create the file and place the file pointer at the begging.
w+ -> open the file for reading and writing.
a -> open the file for writing and place the file pointer at the end of file contents.





3. Reading a file -

PHP fread() function is used to read a file. Before reading a file, we need to open it. So first open a file using fopen() function, then read the file using fread() function.

Syntax - fread('filename', 'filesize')

filesize() function is used to get filesize.

Example -

<?php
    $file_name = 'text.txt';
    $file = fopen($file_name, 'r');
    $file_size = filesize($file_name);
    $file_content = fread($file, $file_size);
    echo $file_size;
    echo $file_content;
?>

4. Writing a file -

fwrite function is used to write in an open file.

Syntax - fwrite('filename', 'content to write');

Example -

<?php
    $file_name = 'text.txt';
    $file = fopen($file_name, 'r');
    $content = 'welcome to etutorialspoint';
    $file_write = fwrite($file, $content);
    if($file_write) {
        echo 'content written to a file';
    }
    else{
        echo 'Failed content written';
    }
?>

5. Closing a file -

fclose() function is used to close a file. This function is called at the end of file operation.

Syntax - fclose()

Example -

<?php
    $file_name = 'text.txt';
    $file = fopen($file_name, 'r');
    $content = 'welcome to etutorialspoint';
    $file_write = fwrite($file, $content);
    if($file_write) {
        echo 'content written to a file';
    }
    else{
        echo 'Failed content written';
    }
    fclose();
?>

Including File

PHP provides function to call external file within a file. There are four include functions in PHP.

  • include('/filepath/filename');
  • require('/filepath/filename');
  • include_once('/filepath/filename');
  • require_once('/filepath/filename');