0% found this document useful (0 votes)
9 views16 pages

CHAPTER 4 (Notes)

The document discusses various topics related to creating web forms and handling form data in PHP, including: 1. Creating forms with different input elements like text boxes, radio buttons, checkboxes, etc. and handling form submission via GET and POST methods. 2. Storing submitted form data in PHP global variables like $_GET, $_POST, $_FILES, $_COOKIE, etc. 3. Differences between HTTP GET and POST methods for form submission and when to use each. 4. Additional topics like form validation, using cookies, sessions, and sending emails from PHP.

Uploaded by

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

CHAPTER 4 (Notes)

The document discusses various topics related to creating web forms and handling form data in PHP, including: 1. Creating forms with different input elements like text boxes, radio buttons, checkboxes, etc. and handling form submission via GET and POST methods. 2. Storing submitted form data in PHP global variables like $_GET, $_POST, $_FILES, $_COOKIE, etc. 3. Differences between HTTP GET and POST methods for form submission and when to use each. 4. Additional topics like form validation, using cookies, sessions, and sending emails from PHP.

Uploaded by

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

CHAPTER 4: Creating and Validating Forms

4.1 Creating a webpage with GUI Components, Browser Role- GET and POST Methods, Server
Role

4.2 Form Controls- Text Box, Text Area, Radio Button, CheckBox, List, Buttons

4.3 Working with Multiple Forms- A web page having many forms, A form having multiple
submit Buttons

4.4 Web Page Validation

4.5 Cookies- Use of Cookies and Attributes of cookies, Create

Cookies, Modify, Delete Cookies

4.6 Session - Use of Session, Start Session, get session variables, destroy session

4.7 Sending Email

Creating Webpages :

• PHP was designed as a web-scripting language, the majority of Web accounts uses PHP for
web page creation.

• A dynamic website may have forms, sessions, and sometimes redirection etc.

• The Web runs on HTTP, i.e. Hyper Text Transfer Protocol.

• This protocol governs how web browsers request files from web servers and how the servers
send the files back.

Variables:

• Server configuration and request information - including form parameters and


cookies - are accessible in three different ways from your PHP scripts.

• Collectively, this information is referred to as EGPCS (environment, GET, POST, cookies,


and server).

• PHP creates six global arrays that contain the EGPCS information.

• The global arrays are:

$_COOKIE: Contains any cookie values passed as part of the request, where the keys of the
array are the names of the cookies.

$_GET: Contains any parameters that are part of a GET request, where the keys of the array are
the names of the form parameters.
$_POST: Contains any parameters that are part of a POST request, where the keys of the array
are

the names of the form parameters

Variables:

$_FILES: Contains information about any uploaded files

$_SERVER: Contains useful information about the web server

$_ENV: Contains the values of any environment variables, where the keys of the array are the
names

of the environment variables.

• These variables are not only global, but are also visible from within function definitions.

• The $_REQUEST array is also created by PHP automatically.

• The $_REQUEST array contains the elements of the $_GET,

$_POST, and $_COOKIE arrays all in one array variable.

• The $_SERVER array contains a lot of useful information from the web server.

• Much of this information comes from the environment variables required in the CGI
specification.

Creating Webpages Cont.:

• When a web browser requests a web page, it sends an HTTP request message to a web server.

• The request message always includes some header information, and it sometimes
also includes a body.

• The web server responds with a reply message, which always

• includes header information and usually contains a body.

• The first line of an HTTP request looks like this:

GET /index.html HTTP/1.1

• This line specifies an HTTP command, called a method, followed by the address of a document
and

the version of the HTTP protocol being used.

Creating Webpages Cont.:


• In this case, the request is using the GET method to ask for the index.html

document using HTTP 1.1.

• After this initial line, the request can contain optional headerinformation that gives
the server additional data about the request.

• For Example:

User-Agent: Mozilla/5.0 (Windows 2000; U) Opera 6.0 [en] Accept: image/gif, image/jpeg,
text/*, */*

• The User-Agent header provides information about the web browser, while the Accept header

specifies the MIME types that the browser accepts.

• After any headers, the request contains a blank line to indicate the end of the header section.

• The request can also contain additional data, if that is appropriate for

the method being used (e.g., with the POST method).

• If the request doesn’t contain any data, it ends with a blank line.

HTTP GET and POST Methods

• The two most common HTTP methods are GET and POST.

• The GET method is designed for retrieving information, such as a document, an image, or the

results of a database query, from the server.

• The POST method is meant for posting information, such as a credit card number or
information

that is to be stored in a database, to the server.

• The GET method is what a web browser uses when the user types in a URL or clicks on a link.

• When the user submits a form, either the GET or POST method can be used, as specified

by the method attribute of the form tag.

HTTP GET and POST Methods Cont.:

• A GET request encodes the form parameters in the URL in what is called a query string; the
text

that follows the ? is the query string:

/path/to/chunkify.php?word=despicable&length=3
• A POST request passes the form parameters in the body of the

HTTP request, leaving the URL untouched.

• The most visible difference between GET and POST is the URL line. Because all of a form’s

parameters are encoded in the URL with a GET request, users can bookmark GET queries.
They

cannot do this with POST requests.

HTTP GET and POST Methods Cont.:

• The HTTP specification says that GET requests are idempotent— that is, one GET request for
a

particular URL, including form parameters, is the same as two or more requests for that URL.

• Thus, web browsers can cache the response pages for GET requests, because the response
page

doesn’t change regardless of how many times the page is loaded.

• Because of idempotent, GET requests should be used only for queries such as splitting

a word into smaller chunks or multiplying numbers, where the response page is never going to

change.

• POST requests are not idempotent. This means that they cannot be cached, and the server is

re-contacted every time the page is displayed.

• What you need to remember is that GET requests should not be used for any actions that
cause a

change in the server, such as placing an order or updating a database.

Sending Data Using get() Method:

<html>

<head> </head>

<body>

<form name=“f1” method=“get” action=“http://localhost/wbp/p1.php”> User Name<input


type=text

name="uname"><br><br> Password<input type=text name="pwd"><br><br>


<input type="submit" name="submit"><br><br>

</form>

</body>

</html>

PHP Script:

<html>

<head> </head>

<body>

<font size=5>

<?php

$user=$_GET['uname'];

$pass=$_GET['pwd'];

echo "The user " .$user . " has logged in with Password " .$pass;

?>

</font>

/body>

</html>

Sending Data Using post() Method:

<html>

<head> </head>

<body>

<form name=“f1” method=“post” action=“http://localhost/wbp/p1.php”>

User Name<input type=text name="uname"><br><br> Password<input type=text


name="pwd"><br><br>

<input type="submit" name="submit"><br><br>

</form>

</body>
</html>

PHP Script:

<html>

<head> </head>

<body>

<font size=5>

<?php

$user=$_POST['uname'];

$pass=$_POST['pwd'];

echo "The user " .$user . " has logged in with Password " .$pass;

?>

</font>

</body>

</html>

Advantages: HTTP GET and POST Methods

• GET

• Since the data sent by the GET method are displayed in the URL, it is possible to bookmark
the

page with specific query string values.

• GET requests can be cached and GET requests to remain in the browser history.

• GET requests can be bookmarked.

• POST

• It is more secure than GET because user-entered information is never visible in the URL
query string or in the server logs.

• There is a much larger limit on the amount of data that can be passed and one can send text

data as well as binary data (uploading a file) using POST.

Disadvantages: HTTP GET and POST Methods


• GET

• The GET method is not suitable for passing sensitive information such as the username and

password, because these are fully visible in the URL query string as well as potentially stored in

the client browser’s memory as a visited page.

• Because the GET method assigns data to a server environment variable, the length of the URL
is

limited. So, there is a limitation for the total data to be sent.

• POST

• Since the data sent by the POST method is not visible in the URL, so it is not possible to
bookmark the page with a specific query.

• POST requests are never cached

• POST requests do not remain in the browser history.

Form Controls:

• <input> Element: The most important form element is the <input> element.

• The <input> element can be displayed in several ways, depending on the type attribute.

• If the type attribute is omitted, the input field gets the default type: "text".

• The <select> element defines a drop-down list.

• The <option> elements defines an option that can be selected. By default, the first item in the

drop-down list is selected.

• To define a pre-selected option, add the selected attribute to the option.

Form Controls:

• There are several form controls as shown below:

Sr.No. Element Description

1. input type=“text” Creates a Text Box

2. input type=“checkbox” Creates a Check Box

3. Input type=“radio” Creates a Radio Button

4. input type=“file” Creates a text box plus button that opens a file
selection dialog

5. input type=“password” Creates a password text box

6. input type=“submit” Creates a submit button

7. input type=“reset” Creates a reset button

8. option An option in a SELECT Element

9. select A listbox

10. Textarea Multiline text box.

Example:

<html>

<body>

<form action=“pform.php" method="GET"> Name: <input type="text" name="name"> <br/>


Age: <input

type="text" name="age"> <br/>

<input type="submit">

</form>

</body>

</html>

Example:

<?php

// name attribute of the input field goes inside the

// square brackets of $_GET superglobal

$name = $_GET["name"];

$age = $_GET["age"];

echo "Your name is ". $name . " and you are ". $age . " years old“;

?>

Output:

Your name is AAA and you are 5 years old


Working With Multiple Forms:

• We can handle multiple forms in PHP while designing a website.

• To create multiple forms, multiple submits need to be created.

• When a form is submitted to a PHP script, PHP automatically creates a special $_POST or
$_GET

associative array, depending on which method of submission was used.

• Values entered into the form input fields are automatically converted to key-value

pairs in this array and can then be accessed using regular array notation.

• When the form is submitted, the submit button itself becomes an element in the $_POST array,

with a key corresponding to its "name". This is clearly visible by adding the line:

print_r($_POST); to the end of the PHP script.

• You can look inside the array and clearly see the correspondence between the form controls
and

their PHP representations.

Branching with if/else:

<html><head>Multi-button form</head>

<body>

<form name="Operate" method="post" action="http://localhost/wbp/mf.php">

Enter a number: <input type="text" name="number" size="3"> <br>

<input type="submit" name="add" value="Add 10">

<input type="submit" name="subtract" value="Subtract10">

<input type="submit" name="mod" value="No">

</form>

</body>

</html>

Branching with if/else:

• Since both submit buttons will invoke the same PHP form processor, the PHP script must be
revised to "know" which one was clicked so it can respond appropriately.

• Since you already know that the submit button appears in the$_POST PHP array and is keyed
by its "name" attribute, it's simple to

(1) give each submit button in the form a unique name and

(2) write a simple "if" test at the top of the PHP form processor to see which of the two keys

appears in the

$_POST array and branch the code appropriately.

Branching with if/else:

<html>

<head> </head>

<body>

<font size=5>

<?php

if (!empty($_POST['add'])) {

print_r($_POST['number']+10);

else if (!empty($_POST['subtract'])) {

print_r($_POST['number']-10);

else{ print_r($_POST['number']); }

?>

</font>

</body>

</html>

Branching with switch/case:

• Depending on which button gets clicked, the appropriate value is passed to the
processing script and the corresponding "case" block is invoked.
• If you have a large number of submit buttons to deal with, this approach is easier to read and

understand than multiple if-else blocks.

Branching with switch/case:

An alternative to previous Example is giving all the submit buttons the same name, but different

values:

<html>

<head>Multi-button from with switch/case</head>

<body>

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

Enter a number: <input type="text" name="number_1" size="3"> <br> Enter another number:
<input

type="text" name="number_2" size="3">

<br>

<input type="submit" name="calculate" value="add">

<input type="submit" name="calculate" value="subtract">

<input type="submit" name="calculate" value="multiply">

</form>

</body>

</html>

Branching with switch/case:

<?php

// branch on the basis of 'calculate' value switch ($_POST['calculate']) {

case 'add': // if calculate => add

echo $_POST['number_1'] . " + " . $_POST['number_2'] . " = " .

($_POST['number_1']+$_POST['number_2']);

break;

case 'subtract': // if calculate => subtract


echo $_POST['number_1'] . " - " . $_POST['number_2'] . " = " .

($_POST['number_1']-$_POST['number_2']);

break;

case 'multiply': // if calculate => multiply

echo $_POST['number_1'] . " x " . $_POST['number_2'] . " = " .

($_POST['number_1'] * $_POST['number_2']);

break;

} ?>

Webpage Validation:

Refer: https://www.w3schools.com/php/php_form_validation.asp

• Validation means check the input submitted by the user.

• There are two types of validations available in PHP as follows -

1) Client-Side Validation - Validation is performed on the client machine web browsers.

2) Server Side Validation - After submitted by data, The data has sent to a server and perform

validation checks in server machine.

Refer https://net-informations.com/faq/asp/validation.htm for more information.

Webpage Validation:

• Some of Validation rules for field are as follows:

Sr.No. Field Validation Rules

1. Name Should required letters and white-spaces

2. Email Should required @ and .

3. Website Should required a valid URL

4. Radio Must be selectable at least once

5. Check Box Must be checkable at least once

6. Drop Down menu Must be selectable at least once

Form Validation Cont.


• Notice that at the start of the script, we check whether the form has been submitted using the

methods like GET, POST etc.

$_SERVER["REQUEST_METHOD"].

• If the REQUEST_METHOD is POST, then the form has been submitted - and it should be
validated.

• If it has not been submitted, skip the validation and display a blank form.

Form Validation Cont.:

• htmlspecialchars() function: All the variables should be passed through this PHP function.

• The html special chars() function converts special characters into HTML entities.

• This means that it will replace HTML characters like < and > with &lt; and &gt;.

• This prevents attackers from exploiting the code by injecting HTML or Javascript code
(Cross-site Scripting attacks) in forms.

• Ex: if a user tries to submit the following in a text field:

<script>location.href('http://www.google.com')</script>

• Then this would not be executed, because it would be saved as HTML escaped code, like this:

&lt;script&gt; location.href('http://www.hacked.com')&lt;/script&gt;

Form Validation Cont.:

• PHP trim(): It is used to strip unnecessary characters (extra space, tab, newline) from the user
input data

• Remove backslashes (\) from the user input data (with the PHP stripslashes() function)

• The next step is to create a function that will do all the checking for us (which is much more

convenient than writing the same code over and over again).

• We will name the function test_input().

Form Validation Cont.:

function test_input($data)

$data = trim($data);
$data = stripslashes($data);

$data = htmlspecialchars($data);

return $data;

Form Validation Cont :

• In the following code we have added some new variables: $nameErr, $emailErr, $genderErr,
and $websiteErr.

• These error variables will hold error messages for the required fields.

• We have also added an if else statement for each $_POST variable.

• This checks if the $_POST variable is empty (with the PHP

empty() function).

• If it is empty, an error message is stored in the different error variables, and if it is not

empty, it sends the user input data through the test_input() function.

Form Validation Cont.:

• The next step is to validate the input data,

• that is "Does the Name field contain only letters and

whitespace?",

• "Does the E-mail field contain a valid e-mail address syntax?",

• "Does the Website field contain a valid URL?"

PHP - Validate Name

• The code below shows a simple way to check if the name field only contains letters and

whitespace. If the value of the name field is not valid, then store an error message:

$name = test_input($_POST["name"]);

if (!preg_match("/ ^[a-zA-Z ]*$ /",$name))

$nameErr = "Only letters and white space allowed";

}
• The preg_match() function searches a string for pattern, returning true if the pattern exists,
and false otherwise.

Valid URL:

• The code below shows a way to check if a URL address syntax is valid (this regular expression
also allows dashes in the URL).

• If the URL address syntax is not valid, then store an error message:

$website = test_input($_POST["site"]);

if(!preg_match("/\b(?:(?:https?|ftp):\/ \ /|www\.)[-a-z0 9+&@#\/%?=~_|!:,.;]

* [-a-z0-9+&@#\/%=~_|]/i", website))

$websiteErr = "Invalid URL";

• Above syntax will verify whether a given URL is valid or not.

• It should allow some keywords as https, ftp, www, a-z, 0-9,..etc..

Valid Email:

• The easiest and safest way to check whether an email address is to use PHP's filter_var()
function.

• In the code below, if the e-mail address is not well-formed, then store an error message:

• Below code shows validation of Email address

$email = test_input($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL))

$emailErr = "Invalid format and please re-enter valid email";

• Above syntax will verify whether given Email address is well-formed or not. If it is not, it will
show an error message.

Valid Email:

<?php
$email = "[email protected]";

// Remove all illegal characters from email

$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo("$email is a valid email address");

} else {

echo("$email is not a valid email address");

?>

You might also like