PHP Form Handling
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.
Example
The example below contains an HTML form with two input fields and a submit button:
1234567
<html><body><form action="welcome.php" method="post">Name: <input type="text" name="name"><br>E-mail: <input type="text" name="email"><br><input type="submit"></form></body></html>
When a user fills out the form above and click on the submit button, the form data is sent to a PHP file, called “welcome.php”:
1 2 3 4 5 6 |
<html> <body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> </body> </html> |
Welcome John
Your email address is [email protected]
Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.
The built-in $_GET function is used to collect values in a form with method=”get”.
i.The $_GET Function
The built-in $_GET function is used to collect values from a form sent with method=”get”. Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser’s address bar) and has limits on the amount of information to send (max. 100 characters).
Example
1 2 3 4 5 |
<form action="welcome.php" method="get"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> |
When the user clicks the “Submit” button, the URL sent to the server could look something like this:
1 |
http://www.msu.ac.zw/welcome.php?fname=Peter&age=37 |
The “welcome.php” file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array):
1 2 |
Welcome <?php echo $_GET["fname"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old |
When to use method=”get”?
When using method=”get” in HTML forms, all variable names and values are displayed in the URL.
Note: This method should not be used when sending passwords or other sensitive information! However, because the variables are displayed in the URL, it is possible to bookmark the page.This can be useful in some cases.
Note: The get method is not suitable for large variable values; the value cannot exceed 100 characters.The built-in $_POST function is used to collect values in a form with method=”post”.
ii.The $_POST Function
The built-in $_POST function is used to collect values from a form sent with method=”post”.Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
Example
1 2 3 4 5 |
<form action="welcome.php" method="post"> Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> |
When the user clicks the “Submit” button, the URL will look like this:
1 |
http://www.msu.ac.zw/welcome.php |
The “welcome.php” file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array):
1 2 |
Welcome <?php echo $_POST["fname"]; ?>!<br /> You are <?php echo $_POST["age"]; ?> years old. |
WAP in php to take input from the user using form and calculate the factorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<html> <body> <form name="calfactorial" method="POST" action=" "> <label for="name"> Enter Your Number for Calculation of Factorial : </label> <input type="number" name="num"><br> <button type="submit" name="submission"> Submit</button> </form> </body> </html> <?php if($_SERVER['REQUEST_METHOD']=="POST") { $number=$_REQUEST['num']; if(empty($number)) { echo "OHH !!! you not provide number so please input number first !!! "."<br>"; } else { function fact ($factnum) { $facts=1; if ($factnum==0) { echo "Factorial of ".$factnum." is : 1 " ; } else { for ($i = 1 ; $i <= $factnum ; $i++) { $facts=$facts*$i; # code... } /* Alternativeldy we can use following code for calculation of factorial. for ($i=$factnum ; $i<=$factnum ; $i--) { $facts=$facts*$i; # code... }*/ print "Factorial of ".$factnum." is : ".$facts; } } fact($number); } } ?> |
Change into UPPER or lower case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<html> <body> <form action="" method="post"> <label>Input Any words : <label/> <input type="text" name="word" value=" <?php if(isset($_POST['WORD'])) { echo ($_POST['WORD']); } ?>"> <button type="submit" name="a">TO UPPER</button> <button type="submit" name="b">to lower</button> </form> <?php if(isset($_POST['a'])) { $name=$_POST['word']; $abcd=strtoupper($name); echo"<br>".$abcd; } if(isset($_POST['b'])) { $name=$_POST['word']; $abcd=strtolower($name); echo"<br>".$abcd; } ?> </body> </html> |
Super Global Variable
Some pre-defined variables are available in php which is know as superglobals variable, which means that they are always accessible, regardless of scope – and you can access them from any function, class or file without having to do anything special.
List of superglobal variables are give below;
- $GLOBALS
- $_SERVER
- $_REQUEST
- $_POST
- $_GET
- $_FILES
- $_ENV
- $_COOKIE
- $_SESSION
1. $GLOBALS variable
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). Using $GLOBALS[index]stores all global variables in an array. Here index hold all variable.
Example
1 2 3 4 5 6 7 8 9 |
<?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; ?> |
2. $_SERVER Variable
$_SERVER is a PHP super global variable which holds information about headers, paths, and script locations.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php echo $_SERVER['PHP_SELF']; echo "<br>"; echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; echo $_SERVER['HTTP_REFERER']; echo "<br>"; echo $_SERVER['HTTP_USER_AGENT']; echo "<br>"; echo $_SERVER['SCRIPT_NAME']; ?> |
3.$_REQUEST Variable
PHP $_REQUEST is used to collect data after submitting an HTML form.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<html> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_REQUEST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?> </body> </html> |
4. $_POST Variable
PHP $_POST is widely used to collect form data after submitting an HTML form with method=”post”. $_POST is also widely used to pass variables.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<html> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_POST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?> </body> </html> |
5. $_FILES Variable
The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors associated with file.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <body> <form action="uploader.php" method="post" enctype="multipart/form-data"> Select File: <input type="file" name="fileToUpload"/> <input type="submit" value="Upload Image" name="submit"/> </form> <?php $target_path = "c:/"; $target_path = $target_path.basename( $_FILES['fileToUpload']['name']); if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) { echo "File uploaded successfully!"; } else { echo "Sorry, file not uploaded, please try again!"; } ?> <body> <html> |
6. $_COOKIE Variable
$_COOKIE is used to create cookie.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php $cookie_name = "user"; $cookie_value = "Hitesh Kumar"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day ?> <!DOCTYPE html> <html> <body> <?php if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set! "; echo "Value is: " . $_COOKIE[$cookie_name]; } ?> <body> <html> |
7. $_SESSION Variable
$_SESSION Variable is used to create session.
$_SESSION Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php // Start the session session_start(); ?> <!DOCTYPE html> <html> <body> <?php // Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set."; ?> <body> <html> |