FILE HANDLING

PHP Open File – fopen():

A better method to open files is with the fopen() function.

PHP Read File – Fread():

The fread() function reads from an open file.

PHP Read Single Line – Fgets():

The fgets() function is used to read a single line from a file.

PHP Write To File – Fwrite():

The fwrite() function is used to write to a file.

r => Open a file for read only. File pointer starts at the beginning of the file

w=> Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file

a=> Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist

(1)TO WRITE A TEXT “this is my file” INTO A FILE NAME IS “abc.txt” Code is use mode “w”:

<?php

$fhandle=fopen(“abc.txt”,”w”);

fwrite($fhandle,”this is my file”);

?>

(2) To read text form “abc.txt “ file using filesize() & fread() function use mode “r”:

<?php

$fhandle=fopen(“abc.txt”,”r”);

$line=fread($fhandle,filesize(“abc.txt”));

echo $line;

?>

(3) To read text form “abc.txt “ file using while loop use mode “r” :

<?php

$file = fopen(“abc.txt”, “r”);

//Output a line of the file until the end is reached

while(! feof($file))

{

echo fgets($file). “<br />”;

}

fclose($file);

?>

(3)how to append new line to file “abc.txt” just use mode “a” :

<?php

$fhandle=fopen(“ok.txt”,”a”);

fwrite($fhandle,”this is my file om maurya”);

 

?>


====

Simple PHP Application to save website content from a website to a file then make search to that file:

Step 1: store website content to a file code given below :

<?php

$curl_handle=curl_init();

 

curl_setopt($curl_handle,CURLOPT_URL,'http://www.vissicomp.com');

 

curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);

 

curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);

 

$buffer = curl_exec($curl_handle);

 

$fhandle=fopen(“example.txt”,”a”);

fwrite($fhandle,$buffer);

 

curl_close($curl_handle);

 

if (empty($buffer))

{

print “Nothing returned from url.<p>”;

}

 

else

{

print $buffer;

}

?>

Step 2 make Search in that file for particular word:

(a)write code for search.html:

<form action=searchst.php method=post>

<input type=text name=search>

<input type=submit name=submit value=submit>

</form>

(b)write code for searchst.php file:

<?php

$search = $_POST[‘search’];

// Read from file

$lines = file(‘example.txt’);

foreach($lines as $line)

{

// Check if the line contains the string we’re looking for, and print if it does

if(strpos($line, $search) !== false)

echo”<html><title>SEARCH RESULTS FOR: $search</title><font face=’Arial’> $line <hr>”;

}

?>