PHP File System

PHP File System Tutorial


This tutorial deals with the opening , closing, reading and writing of file. There are dedicated function for performing these operations in PHP. In order to open a file, fopen() can be used. Calling this function typically requires two parameters namely filename and the mode in which the programmer wishes to open the file. The different modes available in PHP are as follows-

Mode Function
r This mode opens the file for only reading. The file pointer points to the first character of the file.
r++ This mode opens the file for reading as well as writing. The file pointer points to the first character of the file.
w this mode opens the file for only writing. The file pointer points to the beginning of the file. Moreover, the file length is truncated to zero. In case the file doesn’t exist, then the system tries to create a file.
w++ This mode opens the file for only writing and reading. The file pointer points to the beginning of the file. Moreover, the file length is truncated to zero. In case the file doesn’t exist, then the system tries to create a file.
A This mode opens the file for only writing. The file pointer points to the end of the file. In case the file doesn’t exist, then the system tries to create a file.
a++ This mode opens the file for only writing and reading. The file pointer points to the end of the file. In case the file doesn’t exist, then the system tries to create a file.

If the requested file is successfully opened, the file pointer for the file is returned. On the other hand, if the file opening operation fails, FALSE is the returned to the calling function, As a rule, be sure to close any file that you open. The function used for this purpose is fclose(), which has been discussed below.

Once a file is open, one of the operations that you will perform is the file reading. This is typically done using fread(), which requires two arguments namely, file pointer and the file length in bytes. If the size of the file is unknown, you can use filesize() function to determine the same and only requires the filename as argument. In order to read a file file, the steps that you will need to follow include-

  • Opening the file using fopen()
  • Determining the size of file using filesize()
  • Reading the contents of the file using fread()
  • Closing the file using fclose()

Same code for demonstrating the different steps involved in the process has been provided below for your reference.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<html>

<head>

<title>PHP File System</title>

</head>

<body>

<?php

$file_name="test.txt";

$file1=fopen($file_namem,"r");

if($file1==false){

echo "File cannot open";

exit();

}

$file_size=filesize($file_name);

$file_text=fread($file1,$file_size);

fclose($file1);

echo "Size of File: $file_size bytes";