File Handling In PHP
PHP includes a lot of built-in functions for handling files and directories. You can read, write, delete, and get lots of information on files through the use of these functions. Before working with files, make sure that you have the right permissions that will allow you to manipulate them.
***************************************************************
Overview of File Processing
There are three steps to write or read data from a file:
Open the file
Write the data to the file or Read data from the file
Close the file
***************************************************************
Opening a File
The fopen() function is used to open files in PHP.
$fp = fopen("filename", "mode");
The first parameter contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The possible values for mode are :
Read: 'r'
Open a file for read only use. The file pointer begins at the front of the file.
Write: 'w'
Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. If the file does not exist, attempt to create it.
Append: 'a'
Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. If the file does not exist, attempt to create it.
Read/Write: 'r+'
Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.
Write/Read: 'w+'
This is exactly the same as r+, except that it deletes all information in the file when the file is opened. If the file does not exist, attempt to create it.
Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of the file. If the file does not exist, attempt to create it.
X
Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This option is supported in PHP 4.3.2 and later, and only works for local files.
x+
Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This option is supported in PHP 4.3.2 and later, and only works for local files.
b
Binary mode – Used in conjunction with one of the other modes
$oldfp = fopen("oldinfo.txt", "r"); //opens a file for reading
if(!$fp = fopen("newinfo.txt", "w")) //tries to open a file for writing
The fopen() function return an integer, also known as a file pointer. This is used later on to work with the opened file. If a file cannot be opened for whatever reason, "fopen()" returns FALSE.
***************************************************************
Closing a File
The next logical step after opening a file and finished your business with it is to close that file down. The function fclose does that and requires the file handle that we want to close down.
bool fclose (resource handle)
The fclose function returns true on success or false on failure.
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') ;
fclose($ourFileHandle);
***************************************************************
Writing to a File
The fwrite function allows data to be written to any type of file.
int fwrite (resource handle, string string [, int length])
The first parameter is the file handle and its second parameter is the string of data that is to be written. The third parameter, length is the maximum number of bytes to write. If this parameter is supplied, fwrite() will write string to the file pointed to by $fp untill it reaches the end of the string or has written length bytes, which ever comes first.
The fwrite() function will return the number of bytes written, or FALSE on error.
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
fclose($fh);
The fputs() Function
int fputs (resource handle, string string [, int length])
The fputs() function is an alias of the fwrite() function.
***************************************************************
Reading an arbitrary length of data
string fread (resource handle, int length)
The fread() function reads up to length bytes from the file pointer referenced by handle. Reading stops when length bytes have been read, EOF (end of file) is reached whichever comes first. If no second variable (length) is specified, it will default to 1k (1024).
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
***************************************************************
Reading from a File Line by Line
The fgets() function is used to read a single line from a file.
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
The fgets function reads data from a file until it reaches a new line "\n", an EOF (end-of-file), or a specified length, in this order.
***************************************************************
Reading from a File Character by Character
The fgetc() function is used to read a single character from a file.
$chr = fgetc($fp); //reads 1 byte only
A side effect of using fgetc() instead of fgets() is that it will return the EOF character whereas fgets() will not. We need to test feof() again we've read the character because we don't want to echo the EOF to the browser.
while(!feof($fp))
{
$char=fgetc(fp);
if(!feof($fp))
echo ($char=="\n" ? "
" : $char);
}
It is not generally sensible to read a file character-by-character unless for some reason we want to process it character-by-character.
***************************************************************
Check for End-of-file
The feof() function checks if the "end-of-file" (EOF) has been reached. This function returns TRUE if an error occurs, or if EOF has been reached. Otherwise it returns FALSE.
The feof() function is useful for looping through data of unknown length.
The file_get_contents() function
It takes the filename as input and returns the contents of a file into a string.
The file_put_contents() function
The file_put_contents writes the data into the file. Its the same as calling fopen(), fwrite() and fclose() in sequence.
CODE
***************************************************************
The readfile() Function
The readfile() function reads a file and writes it to the output buffer.
This function returns the number of bytes read on success, or FALSE and an error on failure.
The fpassthru() function dumps the contents of the file fro the current pointer position onwards to the standard output. It closes the file when it is finished. The function returns true if the read is successful and false otherwise.
$fp=fopen("a.txt","r");
fpassthru($fp);
The file() function is also used to reads the entire file and returns as an array. Each line of the file is stored in a separate element of the array.
$filearray=file$fp);
Reading the size of a file
filesize(filename)
The filesize() function returns the size of the specified file.
This function returns the file size in bytes on success or FALSE on failure.
"touch()" searches if a file exists, and if it doesn't, it creates one, according to the specified filename; "unlink()" is used to remove the file passed on as an argument:
touch("newinfo.txt"); //create a new file, if it doesn't already exist
unlink("oldinfo.txt"); //delete a file
You now have enough information to read a file line by line:
$filename = "test.txt";
$fp = fopen($filename, "r") or die("Couldn't open $filename");
while(!feof($fp))
{
$line = fgets($fp);
print "$line
";
}
fclose($fp);
While "fgets()" works well around text files, you may sometimes want more functionality for your script. The "fread()" functions returns the specified amount of data from a file, and doesn't take into consideration the end-of-line "\n", like "fgets()". "fread()" also starts from the current file position, but if you're not happy with it, you can always change it using the "fseek()" function.
fseek($fp, 100); //moves the file pointer to the 100th byte
print(fread($fp, 15)); //outputs 15 bytes
Any writing to a file is done with the use of "fwrite()" or "fputs()" functions, which both use a file pointer and a string to perform the writing:
fputs($fp, "Hello again from PHP!");
However, on public web-sites, with many users accessing your scripts at the same time, your files could quickly become corrupt. PHP offers the "flock()" function, which will lock a file and won't allow other processes to write or read the file while the current process is running. "flock()" requires a file pointer and an integer to do this:
flock($fp1, 1); //shared lock – allows read, doesn't allow write
flock($fp2, 2); //exclusive lock – doesn't allow neither read, nor write
flock($fp3, 3); //release lock – releases a shared or exclusive lock
***********************************************************
No comments:
Post a Comment