Web Technologies - Old Questions

13.  Differentiate between file handling and form handling.


5 marks | Asked in 2069

File handling

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);
?>

Form Handling

Handling forms is a multipart process. First a form is created, into which a user can enter the required details. This data is then sent to the web server, where it is interpreted, often with some error checking.

PHP Form Handling with POST:

If we specify the form method to be POST, then the form-data is sent to the server using the HTTP POST method.

syntax:

<?php

 $_POST['variable_name'];

?>

E.g. 

//form1.html

<form action="login.php" method="post">   

<table>   

<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>  

<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>   

<tr><td colspan="2"><input type="submit" value="login"/>  </td></tr>  

</table>  

</form>   

//login.php

<?php  

$name=$_POST["name"];   //receiving name field value in $name variable  

$password=$_POST["password"];   //receiving password field value in $password variable  

echo "Welcome: $name, your password is: $password";  

?>  

PHP Form Handling with GET:

If we specify the form method to be GET, then the form-data is sent to the server using the HTTP GET method.

syntax:

<?php

$_GET['variable_name'];

?>

E.g. 

//form1.html

<form action="welcome.php" method="get">  

    Name: <input type="text" name="name"/>  

    <input type="submit" value="visit"/>  

</form>  

//welcome.php

<?php  

$name=$_GET["name"];    //receiving name field value in $name variable  

echo "Welcome, $name";  

?>