Web Technologies - Old Questions

12.  Discuss server side file handling with example.

5 marks | Asked in 2071

File handling simply deal with creating, reading, deleting and editing files. Website can handle local files. It can read from, and write to, a text file on the disk. The code can run on any server with file system privileges—and also a local development machine

There are some methods of File which are used in PHP:

PHP Open File - fopen():
fopen() function opens the file. The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. E.g.
    $myfile = fopen("webdictionary.txt""r"

PHP Read File - fread():
The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read. The following PHP code reads the "webdictionary.txt" file to the end:
    fread($myfile,filesize("webdictionary.txt"));

PHP Close File - fclose():
The fclose() function is used to close an open file. E.g.
    fclose($myfile);

PHP Write to File - fwrite():
The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written. E.g.
<?php
$myfile = fopen("newfile.txt""w"or die("Unable to open file!");
$txt = "Hello bro!\\n";
fwrite($myfile, $txt);
fclose($myfile);
?>