pTutorial

New way to learn PHP

PHP 5 File open | close | read

File handling

In this section we will learn how open, close, and read file data on server or you can say that how to manipulate the file on server


We will use the txt file, demo.txt during the learning. The content of file are following below.

To be available and stable, the information needs to be stored somewhere secure.
where no one can access or modify.

Modes of file

Modes of file
Value Description Pointer
r Open the file for reading only. At the beginning
r+ Open the file for read or write. At the start
w Open the file for writing only. Existing content will be lost.
w+ Open the file for reading and writing. Existing content will be lost.
a Open the file for appending only. PHP attempts to create it.
a+ Open the file for reading and appending. PHP attempts to create it.

PHP open file using fopen()

fopen function is used for opening existing file on your server. Its takes two argument. If fopen function unable to the file its return zero otherwise one ( 1 ) .

Syntax of fopen

int fopen (string file, string mode);

First parameter is name of file in the form of string that means single or double quoted and second parameter is mode of file that are given in above tabale.

PHP fread fuction

Fread function is used to read up to the number of bytes, unless it reaches the end of the file first. It return false if data does not read successfully.

Syntax of fread function

string fread (int filepointer, int length)

First parameter is a integer type variable and it must point to an opened file. Second parameter is number of byte you want to read.

Note: Reading will stop either length of bytes have been read or end of the file has been reached.

Example

<?php

$fh = fopen('demo.txt', "r") ;

$file = fread($fh, 25);

print $file;

fclose($fh);

?>

Output

To be available and stabl

fclose function

fclose function is used to close an open file pointed by the open file variable. It return false if the file does not close properly.

Syntax of fclose

fclose($fh);

Read entire file example

<?php

$fh = fopen('ptutorial.txt', "r") ;

$file = fread($fh, filesize('ptutorial.txt'));

print $file;

fclose($fh);

?>

Here filesize function is used to calculate the number of byte used by the file.

Output

To be available and stable, the information needs to be stored somewhere secure. where no one can access or modify.

QUOTES OF THE DAY

Knowledge itself is a power.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER