[go: up one dir, main page]

0% found this document useful (0 votes)
62 views31 pages

Unit - 4 PHP - 5

The document discusses various topics related to forms in PHP including creating and using forms, GET vs POST methods, processing form data, validating form input, and more. It provides code examples to demonstrate how to create a basic registration form with PHP, process submitted form data, and validate different form field types like strings, numbers, emails. It also discusses using client-side and server-side validation.

Uploaded by

srinivas890
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views31 pages

Unit - 4 PHP - 5

The document discusses various topics related to forms in PHP including creating and using forms, GET vs POST methods, processing form data, validating form input, and more. It provides code examples to demonstrate how to create a basic registration form with PHP, process submitted form data, and validate different form field types like strings, numbers, emails. It also discusses using client-side and server-side validation.

Uploaded by

srinivas890
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

K Mahesh

RCEW, Pasupula (V), Nandikotkur Road,


Near Venkayapalli, KURNOOL
Syllabi
• Creating and Using Forms Understanding
Common Form Issues, GET vs. POST, Validating
form input, Working with multiple forms, and
Preventing Multiple Submissions of a form.
• XML: Basic XML- Document Type Definition XML
Schema DOM and Presenting XML, XML Parsers
and Validation, XSL and XSLT Transformation,
News Feed (RSS and ATOM).
Forms
• To create a fully functional web application, you need to
be able to interact with your users.
• The common way to receive information from web users
is through a form. Web forms are only Hypertext Markup
Language (HTML) elements.
• PHP 5 is built so that it seamlessly integrates with form
elements.
• Over the past few versions of PHP, its methodology for
dealing with form information has gradually evolved and
is now quite robust.
<form>...</form>
• When you login into a website or into your mail box, you are
interacting with a form.
• Forms are used to get input from the user and submit it to the web
server for processing.
•  The diagram below illustrates the form handling process.
• A form is an HTML tag that contains graphical user interface items
such as input box, check boxes radio buttons etc.
• The form is defined using the <form>...</form> tags and GUI items
are defined using form elements such as input.
Create a form
• use HTML tags to create a form.
• Opening and closing form tags <form>…</form>
• Form submission type POST or GET
• Submission URL that will process the submitted data
• Input fields such as input boxes, text areas,
buttons,checkboxes etc.
• <input type="hidden" name="form_submitted"
value="1"/> is a hidden value that is used to check
whether the form has been submitted or not
• <input type="submit" value="Submit"> is the button
that when clicked submits the form to the server for
processing
<html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>

<h2>Registration Form</h2>

<form action="registration_form.php" method="POST"> First name:

<input type="text" name="firstname"> <br> Last name:

<input type="text" name="lastname">

<input type="hidden" name="form_submitted" value="1" />

<input type="submit" value="Submit">

</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>Thank You <?php echo $_POST['firstname']; ?> </h2>

<p>You have been registered as


<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>

<p>Go <a href="/registration_form.php">back</a> to the form</p>

<?php else: ?>

<h2>Registration Form</h2>

<form action="registration_form.php" method="POST">

First name:
<input type="text" name="firstname">

<br> Last name:


<input type="text" name="lastname">

<input type="hidden" name="form_submitted" value="1" />

<input type="submit" value="Submit">

</form>

<?php endif; ? >


</body>
</html>
Simple search engine
• design a simple search engine that uses the
PHP_GET method as the form submission
type.
<html>
<head>
<title>Simple Search Engine</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>

<?php if (isset($_GET['form_submitted'])): ?>

<h2>Search Results For <?php echo $_GET['search_term']; ?> </h2>


<?php if (isset($_GET['search_term'])):

header('Location: https://www.google.com/search?q='.$_GET['search_term']);
?>
<p>The GET method displays its values in the URL</p>

<?php else: ?>


<p>Sorry, no matches found for your search term</p>

<?php endif; ?>

<p>Go <a href="searcheng.php">back</a> to the form</p>

<?php else: ?>

<h2>Simple Search Engine - Type in GET </h2>

<form action="searcheng.php" method="GET">

Search Term:
<input type="text" name="search_term">
<br>

<input type="hidden" name="form_submitted" value="1" />


<input type="submit" value="Submit">

</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.

preg_match(pattern, input, matches, flags, offset)

$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

• Prevent multiple form submissions using


Javascript
• prevent multiple form submissions using
cookies
• prevent multiple form submissions using
sessions
using Javascript
• Using Javascript to block duplicate submissions is
probably the easiest way. When someone submits
the form we simply disable the Submit button and
maybe change it's value to something more
descriptive, like "Submitting, please wait..."

<input type="submit" value="Submit" id="myButton" />

<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

You might also like