Unit - 4 PHP - 5
Unit - 4 PHP - 5
<h2>Registration Form</h2>
</form>
</body>
</html>
GET vs POST Methods
POST GET
Values not visible in the URL Values visible in the URL
Has not limitation of the length of the values Has limitation on the length of the values
since they are submitted via the body of HTTP usually 255 characters. This is because the
values are displayed in the URL. Note the
upper limit of the characters is dependent on
the browser.
Has lower performance compared to Php_GET Has high performance compared to POST
method due to time spent encapsulation the method dues to the simple nature of
Php_POST values in the HTTP body appending the values in the URL.
Supports many different data types such as Supports only string data types because the
string, numeric, binary etc. values are displayed in the URL
Results cannot be book marked Results can be book marked due to the
visibility of the values in the URL
<?php <?php
$_POST['variable_name']; $_GET['variable_name'];
?> ?>
Processing the registration form data
• The registration form submits data to itself as
specified in the action attribute of the form.
• When a form has been submitted, the values are
populated in the $_POST super global array.
• Use the PHP isset() function to check if the form
values have been filled in the $_POST array and
process the data.
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php if (isset($_POST['form_submitted'])): ?> //this code is executed when the form is submitted
<h2>Registration Form</h2>
First name:
<input type="text" name="firstname">
</form>
header('Location: https://www.google.com/search?q='.$_GET['search_term']);
?>
<p>The GET method displays its values in the URL</p>
Search Term:
<input type="text" name="search_term">
<br>
</form>
<?php endif; ?>
</body> </html>
Validating form input
• Validation is a way to catch mistakes when they happen
(or even better, to prevent them from happening at all).
• Client-side validation: These are the checks that happen
in the browser, before a form is submitted. The goal here
is to make life easier for the people filling out the form.
• Examples: HTML5, JavaScript etc.
• Server-side validation: These are the checks that happen
after a form is sent back to the web server. At this point,
it is up to your server-side code to review the details and
make sure everything is proper before continuing. No
matter what the browser does, server-side validation is
essential.
Client-side validation
• HTML
• JavaScript
• CSS
• Example
Server-side validation
• HTML
• CSS
• PHP
• Example
Validating form input
• An HTML form contains various input fields such as text box,
checkbox, radio buttons, submit button, and checklist, etc.
• These input fields need to be validated, which ensures that the
user has entered information in all the required fields and also
validates that the information provided by the user is valid and
correct.
• There is no guarantee that the information provided by the user is
always correct. PHP validates the data at the server-side, which is
submitted by HTML form. You need to validate a few things:
– Empty String
– Validate String
– Validate Numbers
– Validate Email
– Validate URL
– Input length
Empty String
• The code below checks that the field is not empty. If
the user leaves the required field empty, it will show
an error message.
• The empty() function checks whether a variable is
empty or not.
if (empty ($_POST["name"])) {
$errMsg = "Error! You didn't enter the Name.";
echo $errMsg;
} else {
$name = $_POST["name"];
}
Validate String
• The code below checks that the field will contain only alphabets and
whitespace,
• Example - name. If the name field does not receive valid input from the
user, then it will show an error message:
• The preg_match() function returns whether a match was found in a string.
$name = $_POST ["Name"];
if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
} else {
echo $name;
}
Validate Number
• The below code validates that the field will only
contain a numeric value.
• For example - Mobile no. If the Mobile no field
does not receive numeric data from the user, the
code will display an error message:
$mobileno = $_POST ["Mobile_no"];
if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
echo $mobileno;
}
Validate Email
• A valid email must contain @ and . symbols.
• PHP provides various methods to validate the
email address.
$email = $_POST ["Email"];
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
if (!preg_match ($pattern, $email) ){
$ErrMsg = "Email is not valid.";
echo $ErrMsg;
} else {
echo "Your valid email address is: " .$email;
}
Input Length Validation
• The input length validation restricts the user to
provide the value between the specified range,
for Example - Mobile Number.
• A valid mobile number must have 10 digits.
$mobileno = strlen ($_POST ["Mobile"]);
$length = strlen ($mobileno);
if ( $length < 10 && $length > 10) {
$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else {
echo "Your Mobile number is: " .$mobileno;
}
Validate URL
• The below code validates the URL of website
provided by the user via HTML form. If the field
does not contain a valid URL, the code will display
an error message.
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-
z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}
Button Click Validate
• The below code validates that the user click on
submit button and send the form data to the
server one of the following method - get or post.
if (isset ($_POST['submit']) {
echo "Submit button is clicked.";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Data is sent using POST method ";
}
} else {
echo "Data is not submitted";
}
Working with multiple forms
• Sometimes you will need to collect values from more
than one page. Most developers do this for the sake of
clarity.
• By providing forms on more than one page, you can
separate blocks of information and thus create a
flexible experience for the user. The problem,
therefore, is how to GET values from each page onto
the next page and finally to the processing script.
• Being the great developer that you are, you can solve
this problem and use the hidden input form type.
When each page loads, you only load the values from
the previous pages into hidden form elements and
submit them.
Example
• Page1.php
• Page2.php
• Page3.php
• Page4.php
Preventing Multiple Submissions of a form
<form
onsubmit="document.getElementById('myButton').disabled=true;
document.getElementById('myButton').value='Submitting, please wait...';“
>
using Cookies
• If you wish to avoid duplicate submissions for the entire
browser session (or longer) you can consider using cookies.
• For example, edit your form processing script to send a cookie
to the browser after the form has been processed but before
any HTML or redirection headers are printed. Placing this code
after the mail() command should work in most cases:
setcookie('FormSubmitted', '1');
if (isset($_COOKIE['FormSubmitted']))
{
die('You may only submit this form once per session!');
}
using Sessions
• Using sessions
<?php
session_start();
if ($_SESSION['formsessions'][$_POST['formsession']]) {
// form already submitted!
// ideally, at this point, you'd want to forward them to another page.
exit('form submitted twice.')
}
// mark the session as submitted.
$_SESSION['formsessions'][$_POST['formsession']]=true;
?>
Global Variables
• document
END