0% found this document useful (0 votes)
54 views

Chapet 4 PHP

The document discusses creating and validating forms in PHP. It covers form elements like input, textarea, select, and button. It also covers the GET and POST methods for form submission and explains server-side validation of form inputs in PHP using functions like empty(), filter_var(), and is_numeric().

Uploaded by

usvirat1805
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Chapet 4 PHP

The document discusses creating and validating forms in PHP. It covers form elements like input, textarea, select, and button. It also covers the GET and POST methods for form submission and explains server-side validation of form inputs in PHP using functions like empty(), filter_var(), and is_numeric().

Uploaded by

usvirat1805
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Chapter-4

Creating and validating Forms


➢ Creating Web Page using GUI Components
✓ Form Tag
• A form is essentially a container for inputs.
• An form is a section of a document which contains controls such as text fields, password fields,
checkboxes, radio buttons, submit button, menus etc.
• An form facilitates the user to enter data that is to be sent to the server for processing such
as name, email address, password, phone number, etc. .
• forms are required if you want to collect some data from of the site visitor.
• The following code shows the basic structure of a form:
<form>
The input elements goes here
</form>

• Syntax

<form action="server url" method="get|post">


//input controls e.g. textfield, textarea, radiobutton, button
</form>

There are two attributes of the form tag that we should be familiar with:
1. The action attribute points to the back-end of our web page, which handles the form
submission
2. The method attribute is used to upload the data. The most commonly used attributes are the
GET and POST methods
• The HTML <form> element can contain one or more of the following form elements:

Tag Description

<input> It defines an input control.

<textarea> It defines a multi-line input control.

<label> It defines a label for an input element.

<fieldset> It groups the related element in a form.

<legend> It defines a caption for a <fieldset> element.

<select> It defines a drop-down list.

<option> It defines an option in a drop-down list.

<button> It defines a clickable button.


1. <input> Element

<input> is a fundamental form element. There are several types of inputs.

State any four form controls to get user’s input in PHP.

1. Textbox control: It is used to enter data. It is a single line input on a web page.

<input type=“text” name=”firstname”>

2. Password control: It is used to enter data that appears in the form of special characters on a web
page inside box. Password box looks like a text box on a wab page.

<input type=“password”>

3. Textarea : It is used to display a textbox that allow user to enter multiple lines of text.

<textarea> … </textarea>

4. Checkbox:It is used to display multiple options from which user can select one or more options.

<input type=“checkbox”>

5. Radio / option button :These are used to display multiple options from which user can select only
one option.
<input type=“radio”>
7. submit button: are used to add a submit button on web page. When user clicks on submit button, then
form get submit to the server.

<input type="submit">

<label> Element
A label can be assigned with a <label> element. The label element makes the browser user-friendly
and provides a focus when you click on a label tag.

<fieldset> element:
The <fieldset> element in HTML is used to group the related information of a form. This element is used with
<legend> element which provide caption for the grouped elements.
<form>
<fieldset>
<legend>User Information:</legend>
<label for="name">Enter name</label><br>
<input type="text" id="name" name="name"><br>
<label for="pass">Enter Password</label><br>
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</fieldset>
<form>
<select>
The <select> element is used to create a drop-down list.
The <select> element is most often used in a form, to collect user input
<select>
<option>New Delhi</option>
<option>Indore</option>
<option>Jaipur</option>
<option>Jodhpur</option>
<option>Chandigarh</option>
<option>Mumbai</option>
<option>Bengaluru</option>
<option>Lucknow</option>
<option>Amritsar</option>
</select>

<button>
The <button> tag is used to create a clickable button within HTML form on your webpage. You can put
content like text or image within the <button>........</button> tag.
<button name="button" value="OK" type="button">Click Here</button>
Design Web page using different form elements.
Design a form using GUI components and display data
submitted on same PHP form
Create customer form like customer name, address, mobile no, date
of birth using different form of input elements & display user
inserted values in new PHP form.

data.php
GET and POST Methods
✓ PHP provides two methods through which a client (browser) can send
information to the server. These methods are given below, and discussed in
detail:

1. GET method
2. POST method

✓ Get and Post methods are the HTTP request methods used inside the <form> tag
to send form data to the server.
✓ HTTP protocol enables the communication between the client and the server
where a browser can be the client, and an application running on a computer
system that hosts your website can be the server.

GET method
✓ The GET method is used to submit the HTML form data. This data is collected by
the predefined $_GET variable for processing.
✓ The information sent from an HTML form using the GET method is visible to
everyone in the browser's address bar, which means that all the variable names
and their values will be displayed in the URL. Therefore, the get method is not
secured to send sensitive information.

POST method
✓ Similar to the GET method, the POST method is also used to submit the HTML
form data. But the data submitted by this method is collected by the predefined
superglobal variable $_POST instead of $_GET.
✓ Unlike the GET method, it does not have a limit on the amount of information to
be sent. The information sent from an HTML form using the POST method is not
visible to anyone.
Web Page Validation in PHP
Invalid user input can make errors in processing. Therefore, validating inputs is a must.
1. Required field will check whether the field is filled or not in the proper way. Most of cases we will use
the * symbol for required field.
2. Validation means check the input submitted by the user.

✓ Validation means check the input submitted by the user.
✓ There are two types of validation are available in PHP.
✓ Client-Side Validation − Validation is performed on the client machine web browsers.
✓ Server Side Validation − After submitted by data, The data has sent to a server and perform
validation checks in server machine

Some of Validation rules for field Validation Rules


Field
Name Should required letters and white-
spaces
Email Should required @ and .
Website Should required a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once
The preg_match() function searches a string for pattern, returning true if the pattern exists, and false
otherwise.
To check whether an email address is well-formed is to use PHP's filter_var() function. empty()
function will ensure that text field is not blank it is with some data, function accepts a variable as an
argument and returns TRUE when the text field is submitted with empty string, zero, NULL or FALSE
value.
Is_numeric() function will ensure that data entered in a text field is a numeric value, the function
accepts a variable as an argument and returns TRUE when the text field is submitted with numeric
value.

Example:
<?php
$name =""; // Sender Name
$email =""; // Sender's email ID
$message =""; // Sender's Message
$nameError ="";
$emailError ="";
$techError ="";
$messageError ="";
$errors=0 ;
$msg="";
if(isset($_POST['submit']))
{ // Checking null values in message.
$name = $_POST["name"]; // Sender Name
$email = $_POST["email"]; // Sender's email ID
$message = $_POST["message"]; // Sender's Message
$technologies = $_POST["radio1"];
if(isset($_POST['radio1']))
{
$technologies = $_POST["radio1"];
}
else
{
$technologies ="";
}
if (empty($_POST["name"]))
{
$nameError = "Name is required";
$errors = 1;
}
if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
$emailError = "Email is not valid";
$errors = 1;
}
if (!isset($_POST["radio1"])){
$techError = "Select one technology";
$errors = 1;
}
if (empty($_POST["message"])){
$messageError = "Message is required";
$errors = 1;
}
else
{
$msg ="Form Submitted successfully..."; // IF no errors
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Contact Form with Validation</title>
<style>
.error
{
color:red;
}
</style>
</head>
<body>
<div >
<div >
<h2>PHP Contact Form with Validation</h2>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Name :</label>
<input class="input" type="text" name="name" value="">
<span class="error"><?php echo $nameError;?></span><br>
<label>Email :</label>
<input class="input" type="text" name="email" value="">
<span class="error"><?php echo $emailError;?></span><br>
<label>Courses :</label>
<div>
<input type="radio" name="radio1" value="PHP" > PHP
<input type="radio" name="radio1" value="HTML" > HTML
<input type="radio" name="radio1" value="PYTHON" > Python
</div>
<span class="error"><?php echo $techError;?></span><br>
<label>Message :</label>
<textarea name="message" value=""></textarea>
<span class="error"><?php echo $messageError;?></span>
<input class="submit" type="submit" name="submit" value="Submit">
<div style="background-color:green"><?php echo $msg;?></div>
</form>
</div>
</div>
</body>
</html>
COOKIE
➢ Introduction:
✓ Cookie is a small piece of information stored as a file (nearly 4KB) on the user's
computer by the web server.
✓ Additionally, a cookie is generated on the server and saved to the client browser.
✓ A cookie is often used to keep track of information such as a username.
✓ The Cookies are stored on the client side.
✓ A cookie takes less space to store data.
✓ The first time when a client sends a request to the server, the server embedded
the cookie along with the response. Next time onwards client sends the request
along with a cookie to the server. In such a way, cookies can be received on the
server side.

✓ You can use cookie to save any data but it should not exceed 1K(1024 bytes) in
size.
✓ With PHP, you can both create and retrieve cookie values.

➢ Types of Cookies
There are two types of cookies, they are:

1. Session Cookie: This type of cookies are temporary and are expire as soon as
the session ends or the browser is closed.
2. Persistent Cookie: To make a cookie persistent we must provide it with an
expiration time. Then the cookie will only expire after the given expiration time,
until then it will be a valid cookie.

➢ Creating a Cookie in PHP


In PHP we can create/set a cookie using the setcookie() function.
syntax

setcookie(name, value, expire, path, domain, secure)


Attributes of cookies:

Parameter Description

name Used to specify the name of the cookie. It is a mandatory argument. Name
of the cookie must be a string.

value Used to store any value in the cookie. It is generally saved as a pair with
name. For example, name is userid and value is 7007, the userid for any
user.
expire Used to set the expiration time for a cookie. if you do not provide any
value, the cookie will be treated as a session cookie and will expire when
the browser is closed.

path Used to set a web URL in the cookie. If set, the cookie will be accessible
only from that URL. To make a cookie accessible through a domain,
set '/' as cookie path.
domain The domain of your web application. It can be used to limit access of
cookie for sub-domains.

secure If you set this to 1, then the cookie will be available and sent only over
HTTPS connection.

➢ Accessing/Reading Cookies Values


✓ To access a stored cookie we use the $_COOKIE global variable.
✓ Use the isset() methods to check whether the cookie is set or not.

Example: Creating and reading session cookie.


Example: Creating and reading Persistent cookie.
➢ Update/Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie() function:
➢ Destroy/Delete cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
SESSION
✓ session is used to store and pass information from one page to another
temporarily (until user close the website).
✓ Session is not stored on the user browser like Cookies, hence it is a more secure
option.
✓ Session variable holds information about one single user, and are available to
all pages in one application.
✓ Session work by creating a unique identification(UID) number for each visitor
and storing variable based on this ID.
✓ Session is not limited by any size limit, you can store any information in the
session, irrespective of its size.
✓ A session ends when the user closes the browser or after leaving the site.
➢Start Session
✓ In PHP we can start a session by using the session_start() function.
✓ And data is stored in the session using session variable.
✓ Session variables are set with the PHP global variable: $_SESSION.

Example:
➢ Getting Session Variable Values

✓ To get/retrieve session variables is to use the $_SESSION variable.

Example
➢Destroy a Session

✓ To remove all global session variables and destroy the session,


use session_unset() and session_destroy():

1. session_unset() : remove all the stored values from the session variable.

2. session_destroy() : destroy the session.

Example:
PHP - Sending Emails
✓ PHP has a built-in mail() function to send an email.
✓ Syntax
mail( to, subject, message, headers, parameters );
✓ mail() function in PHP requires three mandatory arguments that specify the
recipient's email address, the subject of the message and the actual message
additionally there are other two optional parameters.

✓ Parameters

• to − Required. Specifies the receiver / receivers of the email


• subject − Required. Specifies the subject of the email. This parameter cannot
contain any newline characters
• message − Required. Defines the message to be sent. Each line should be
separated with a LF (\n). Lines should not exceed 70 characters
• headers − Optional. Specifies additional headers, like From, Cc, and Bcc. The
additional headers should be separated with a CRLF (\r\n)
• parameters − Optional. Specifies an additional parameter to the send mail
program

✓ Multiple recipients can be specified as the first argument to the mail() function
in a comma separated list.

<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$header = "From:[email protected] ";
$retval = mail ($to,$subject,$message,$header);
if( $retval == true )
{
echo "Message sent successfully...";
}
else
{
echo "Message could not be sent...";
}
?>

You might also like