This page looks best with JavaScript enabled

File Handling and Streams in PHP

 ·  ☕ 2 min read  ·  🤖 Arjit Sharma

Note :

  • ftell($file) : Tells where file pointer is
  • When a file is too big ,u cant read entire file in memory in single go then u need to read it in chunks.

Streams

A stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion.
We use Streams to provide data on demand.( Providing data in chunks )

Opening a file in PHP

1
2
$file = fopen(__DIR__ . '/empList.txt','r+') or die("Unable to open");
        //r+ : read-write mode and others like,w,r,a

Reading a file in PHP

Reading 1 line

1
2
$employee = fgets($file);
echo $employee;

Read whole file

1
2
3
4
5
6
7
//Reading in 1 call(won't work for big files)
$fileData = fread($file,filesize($file));

//Reading line by line
while(!feof($file)){
    echo fgets($file) . "<br>";
}

Read file to string

Using file_get_contents()

1
2
$text = file_get_contents("files/my_file.txt");
echo $text;

Writing to a file

1
2
3
$newFile = fopen("newFile.txt", "w") or die("Unable to open file");
$line = "Hello World, Add this line to file";
fwrite($newFile,$line);

Deleting a file

1
unlink("file.txt");

Stream Wrappers

Tells the stream how to handle specific protocols. ex-https,ftp,zip

Stream Context

Set of parameters or wrapper specific options
stream_context_create() : Creates and returns a stream context with any options supplied in options preset.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts); ?>
Share on

Arjit Sharma
WRITTEN BY
Arjit Sharma
Yo, I am a CS enthusiast or am I ? Just kidding.


What's on this Page