PHP File Functions

PHP File Functions

integer fopen (string filename, string mode)

This function is used to open the file before writing or reading the contents of the file.
For example:

<?
if(!($myFile = fopen ("http://localhost/php/mydata.txt", "r")))
{
    print ("Failed to open file");
}
while (!feof($myFile))
{
    $line = fgetss($myFile,255);
    print ("$line \n");
}
fclose ($myFile);
?>

To know in detail the fopen function, please try it yourself with the various existing modes such as those listed below :

r[b] read only process [binary]

w[b] write process only, if the file is not there then it will be a new file, if the file already exists then the contents of the file will be overwritten by the contents of the new file [binary]

a[b] add the contents of an existing file [binary]

r+[b] read and write [binary]

w+[b] read and write, if the file does not exist it will be a new file, if the file already exists then the contents of the file will be overwritten by the contents of the new file [binary]

a+[b] read and write, the contents of files recently added after the last line on an existing file [binary]

string fgets (integer file_handle, integer length)
This function is used to read a string or contents of a file.
For example:
<?
if($MyFile = fopen("mydata.txt", "r"))
{
while (!feof($MyFile))
{
    $MyLine = fgets ($MyFile, 255);
    print ($MyFile);
}
fclose ($MyFile);
?>

If you run the script above, which appears in the browser is the content of the file mydata.txt.

boolean fclose (integer file_handle)
Used to close the file.

boolean feof (integer file_handle)
This function will return true if the pointer is located at the end of the file (last line).
while (!feof($MyFile))
{
    $MyLine = fgets ($MyFile, 255);
    print ($MyFile);
}

The above example means if it has not reached the "last line" of the file yet (the last pointer position) then the program will continue to read the contents of the file. It means that the program will read the entire contents of the file.
boolean file_exists (string filename)
This function will return true if the file being read exists.
<?
if (file_exists("mydata.txt"))
{
    print ("There is a file mydata.txt ");
}
else
{
    print ("There is not fiel mydata.txt ");
}

If the current directory contained the file mydata.txt, the program will display the words "There is a file mydata.txt" (do not use quotation marks).

0 comments:

Post a Comment