Jul 26, 2011

Dealing With Files In PHP

In php and of course othe languages files are the directories or paths to a given data. file() —> Reads entire file into an array. for example:
array file(string $filename[,int $flags = 0 [,resource $context ]] );
$domain = file('http://www.example.com/');
You can iterate through a given directory read and store an array of data into a variable.

 

file_exists() —> Checks whether a file or directory exists, it returns false if no directory exist. for example:
bool file_exists ( string $filename );
Lets have some example that test weather file exist.
 

Reading and Writing to the file.
The following are the functions that in most cases used in dealing with file reading or crteation:

fpassthru() - Output all remaining data on a file pointer
fopen() - Opens file or URL
include() - include a file
require() - the required file require
file_get_contents() - Reads entire file into a string

feof() — Tests for end-of-file on a file pointer,returns false on error.
bool feof ( resource $handle )

fopen() is use to open a given file, if no file found, the file is created as long as you created a context for appending or writting to the file(a,a+,w,w+....etc).

 
 
File Creation and Deletion
Ok lets have a complete example of file creation and deletion, supposing we have a data.txt database file that contain a data or no data at all, and we want to insert some data in the database and later delete some of these data from it.
We assumed that we have a form that submit an email address, first we have to make sure that the email does not exists in the database before adding it to the existing data using file pointer 'fp' reference passing the read 'r' and appending 'a+' context in the fopen() function as a parrameter.
addEmail.php


delete.php
Now lets delete an existing email from the database. This time arround passing the write context 'w' in the parrameter.


No comments:

Post a Comment