Unit 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Unit 4 Creating and Validating Forms SVERI

Unit 4 Creating and Validating Forms


4.1 Creating web page using GUI components, Browser Role-GET and POST Methods,
Server Role

4.2 Form controls:


 Textbox
 Textarea
 Radio button
 Check box
 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
 Attributes of cookies
 Create cookies
 Modify cookies value
 Delete cookies

4.6 Session-
 Use of session
 Start session
 Get session variable
 Destroy session

4.7 Sending E-mail

Prepared by:-Mr.Pramod Mane Page 1


Unit 4 Creating and Validating Forms SVERI
4.1 Creating web page using GUI components, Browser Role-GET and POST Methods,
Server Role

Browser Role-GET and POST Methods:-

 There are two ways the browser client can send information to the web server.

The GET Method The POST Method

 Before the browser sends the information, it encodes it using a scheme called URL
encoding.

 In this scheme, name/value pairs are joined with equal signs and different pairs are
separated by the ampersand.

 name1=value1&name2=value2&name3=value3

 Spaces are removed and replaced with the + character and any other non alphanumeric
characters are replaced with a hexadecimal values.

 After the information is encoded it is sent to the server.

The GET Method

 GET is used to request data from a specified resource.

 The GET method sends the encoded user information appended to the page request.

 The page and the encoded information are separated by the ? character.

http://www.test.com/index.htm?name1=value1&name2=value2

 The GET method produces a long string that appears in your server logs, in the browser's
Location: box.

 The GET method is restricted to send to characters

 Never use GET method if you have password or other sensitive information to be sent to
the server.

 GET can't be used to send binary data, like images or word documents, to the server.

 The data sent by GET method can be accessed using QUERY_STRING environment
variable.

 The PHP provides $_GET associative array to access all the sent information using GET
method.

Prepared by:-Mr.Pramod Mane Page 2


Unit 4 Creating and Validating Forms SVERI
The POST Method

 POST is used to send data to a server to create/update a resource.

 The POST method transfers information via HTTP headers.

 The information is encoded as described in case of GET method and put into a header
called QUERY_STRING.

 The POST method does not have any restriction on data size to be sent.

 The POST method can be used to send ASCII as well as binary data.

 The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.

 The PHP provides $_POST associative array to access all the sent information using
POST method.

GET vs. POST

 Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3
=> value3, ...)). This array holds key/value pairs, where keys are the names of the form
controls and values are the input data from the user.

 Both GET and POST are treated as $_GET and $_POST. These are super global, 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.

 $_GET is an array of variables passed to the current script via the URL parameters.

 $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?

 Information sent from a form with the GET method is visible to everyone (all variable
names and values are displayed in the URL).

 GET also has limits on the amount of information to send.

 the variables are displayed in the URL, it is possible to bookmark the page.

 GET may be used for sending non-sensitive data.

 Note: GET should NEVER be used for sending passwords or other sensitive information!

Prepared by:-Mr.Pramod Mane Page 3


Unit 4 Creating and Validating Forms SVERI
When to use POST?

 Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request)

 no limits on the amount of information to send.

 Moreover POST supports advanced functionality such as support for multi-part binary
input while uploading files to server.

 However, because the variables are not displayed in the URL, it is not possible to
bookmark the page.

Program:- GET Method


<?php

if(isset($_GET["s1"]))
{
echo "welcome ".$_GET['name']."<br>";
echo "your age ".$_GET['age']." years old";
}
?>

<html>
<body>
<form action="<?php $_PHP_SELF ?>"method="GET">

Name:<input type="text" name="name"/><br>


Age:<input type="text" name="age"/><br>

<input type="submit" name="s1" value="Submit"/>

</form>
</body>
</html>
Output:-

Prepared by:-Mr.Pramod Mane Page 4


Unit 4 Creating and Validating Forms SVERI
Program:- POST Method
<?php

if(isset($_POST["s1"]))
{
echo "welcome ".$_POST['name']."<br>";
echo "your age ".$_POST['age']." years old";
}
?>
<html>
<body>
<form action="<?php $_PHP_SELF?>"method="POST">

Name:<input type="text" name="name"/><br>


Age:<input type="text" name="age"/><br>

<input type="submit" name="s1" value="Submit"/>

</form>
</body>
</html>
Output:-

Prepared by:-Mr.Pramod Mane Page 5


Unit 4 Creating and Validating Forms SVERI

Server Role:-
PHP is server-side scripting language

Using PHP we can create dynamic web sites

That means its processing happens in server by consuming servers resources and sends only
the output to the client.

In client-side scripting language like JavaScript, processing happens in the clients computer
consuming client resources .

Prepared by:-Mr.Pramod Mane Page 6


Unit 4 Creating and Validating Forms SVERI
Program:
<html>
<head>
<title> Welcome to our website</title>
</head>
<body>
<h1>
<?php
if (date('G') < 12)
{
echo "Good Morning";
}
else
{
echo "Good Afternoon";
}
?>
</h1>
</body>
</html>
Output:-

Prepared by:-Mr.Pramod Mane Page 7


Unit 4 Creating and Validating Forms SVERI
4.2 Form controls
 Textbox
 Textarea
 radio button
 check box
 List
 Buttons (Submit,Reset)

1.Textbox:-

 A text input field allows the user to enter a single line of text

Syntax:
<input type="text" name="user"/>
Where,
input type=text,
name=variable_name
Program:-Textbox.html

<html>
<body>
<form action="textbox.php"method="GET">
UserName:<input type="text" name="user"/><br>
<input type="submit" name="s1" value="Submit"/>

</form>
</body>
</html>
Output:-

textbox.php
<?php

echo "Welcome <b>".$_GET ['user']."</b><br/>";


?>
Output:-

Prepared by:-Mr.Pramod Mane Page 8


Unit 4 Creating and Validating Forms SVERI
2.Textarea:-
 It is same as text input field,
 It allows multiple lines of text.
Syntax :-
<textarea name="address" rows="2" cols="40"></textarea>
Where,
Tag:- <textarea> </textarea>
name=variable_name
rows=no of rows required
cols=no of columns required
Program:-
textarea.html
<html>
<body>
Enter Your Address:-

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

<textarea name="address" rows="5" cols="60"> </textarea>

</br></br>
<input type="submit" name="s1" value="Submit"/>
</form>
</body>
</html>
Output:-

textarea.php
<?php
echo "Your Address is </br><b>".$_GET ['address']."</b><br/>";
?>
Output:-

Prepared by:-Mr.Pramod Mane Page 9


Unit 4 Creating and Validating Forms SVERI
3.Radio Button:-
 Its is used for single choice from multiple options
 All radio buttons in the group have the same name attribute
Syntax :-
<input type="radio" name="color" value="Red" />
Where,
input type=radio
name=variable_name //same for all options in button groups
value=value of variable
Program:-
Radiobutton.html
<html>
<body>
<form action="radiobutton.php"method="GET">

<b> Please select your favorite color</b></br>

<input type="radio" name="color" value="Pink">Pink


<input type="radio" name="color" value="Red">Red
<input type="radio" name="color" value="Black">Black
<input type="radio" name="color" value="Orange">Orange
<input type="radio" name="color" value="Green">Green
</br></br>
<input type="submit" name="s1" value="Submit"/>
</form>
</body>
</html>
Output:-

radiobutton.php
<?php
$c=$_GET['color'];
if (($c!=null))
{
echo "You Selected favorite color is <b>".$_GET ['color']."</b>";
}
?>
Output:-

Prepared by:-Mr.Pramod Mane Page 10


Unit 4 Creating and Validating Forms SVERI
4.Checkbox:-
 A checkbox field is a simple toggle button It can be either ON or OFF.
 The value attribute should contain the value that will be sent to the server when the
checkbox is selected. If the checkbox isn’t selected, nothing is sent.
 By creating multiple checkbox fields with the same name attribute, we can allow the user
to select multiple values for the same field.

Syntax :-
<input type="checkbox" name="check_list[]" value="C/C++">C/C++>
Where,
input type= checkbox
name=variable_name //same for all options in button groups
value=value of variable
Program:-
Checkbox.html
<html>
<body>
<form action="checkbox.php"method="GET">

<b> Select your favorite Programming Language</b></br>

<input type="checkbox" name="check_list[]" value="C/C++">C/C++


<input type="checkbox" name="check_list[]" value="Java">Java
<input type="checkbox" name="check_list[]" value="PHP">PHP
<input type="checkbox" name="check_list[]" value="Python">Python

</br></br>

<input type="submit" name="s1" value="Submit"/>


</form>
</body>
</html>
Output:-

Prepared by:-Mr.Pramod Mane Page 11


Unit 4 Creating and Validating Forms SVERI
checkbox.php
<?php
if(isset($_GET['s1']))
{
if(!empty($_GET['check_list']))
{
//couting no of checked checkbox
$checked_count =count($_GET['check_list']);
echo "You have Selected follwing ".$checked_count." options: </br>";

foreach($_GET['check_list']as $selected)
{
echo "<p>".$selected."</p>";
//echo $selected ;
}
}
else
{
echo "<b>Please select at lest one option.</b>";
}
}

?>
Output:-

Prepared by:-Mr.Pramod Mane Page 12


Unit 4 Creating and Validating Forms SVERI
5. List
 The list represents a Windows control to display a list of items to a user.
 A user can select an item from the list.
 users can either select one option from a list or multiple options, depending on the type of
list.
 A multi-select list allows the user to select multiple items at once by holding down Ctrl or
Command key.
 To turn normal list into a multi-select list, add the attribute multiple with a value of
"multiple” to the select element
Syntax :-
<select name="Transport[]" multiple="multiple" </select>
<option>Bus</option>
Where,
multiple="multiple"
name=variable_name
<option>Bus</option>=Values of list
Program:-
Listbox.html
<html>
<body>
<form action="listbox.php"method="GET">

<p> <select name="Transport[]" multiple="multiple"


<option>Bus</option>
<option>Car</option>
<option>Bike</option>
<option>Aroplane</option>
<option>Railway</option>

</select>
</br></br>
<input type="submit" name="s1" value="Submit"/>
</form>
</body>
</html>
Output:-

Prepared by:-Mr.Pramod Mane Page 13


Unit 4 Creating and Validating Forms SVERI
listbox.php

<?php
if(is_array($_GET['Transport']))
{
print "<p> Your Are Selected:</p>";
print "<ol>";//order list ul---unorder list

foreach($_GET['Transport']as $value)
{
print "<li>".$value."</li>\n"; //li----list item
//echo " $value ";
}
print "<ol>";
}

?>

Output:-

Prepared by:-Mr.Pramod Mane Page 14


Unit 4 Creating and Validating Forms SVERI
6.Buttons
 A button is a control, which is an interactive component that enables users to
communicate with an application which we click and release to perform some actions.
 The button control represents a standard button that reacts to a Click event.
 A button can be clicked by using the mouse, ENTER key, or SPACEBAR if the button
has focus
 The buttons element is used to create an HTML button Any text appearing between the
opening
 and closing tags will appear as text on the button.
 No action takes place by default when a button is clicked.
Types of Buttons
 Submit: The button is a submit button (submits form data.

 Reset: The button is a reset button (resets the form-data to its initial values)

Syntax :-
Submit <input type="submit" name="button1"class="button" value="ADD" />

Reset <button type="reset" value="Reset">Reset</button>


Where,
input type= submit or button type=reset
name=variable_name
value=value of variable
Program:-
button.php
<html>
<body>
<h4>How to call PHP function on the click of a Button ? </h4>
<?php

if(array_key_exists('button1', $_POST)) //if button1 or button2 click


{
button1(); //ADD
}
else if(array_key_exists('button2', $_POST)) //button2 button2
{
button2(); //Sub
}
function button1() //ADD
{
if(isset ($_POST['button1']))
{
$a=$_POST['a'];//10
$b=$_POST['b'];//20
$sum=$a+$b;

Prepared by:-Mr.Pramod Mane Page 15


Unit 4 Creating and Validating Forms SVERI
echo "Addition of $a and $b is:".$sum;
}
}
function button2() //Substractions
{
if(isset ($_POST['button2']))
{
$a=$_POST['a'];
$b=$_POST['b'];
$sub=$a-$b;
echo "Substractions of $a and $b is:".$sub;
}
}
?>

<form method="post">

Enter Value of a:-


<input type="number" name="a"/><br><br>

Enter Value of b:-


<input type="text" name="b"/><br><br>

<input type="submit" name="button1"class="button" value="ADD" />

<input type="submit" name="button2"class="button" value="SUB" />

<button type="reset" value="Reset">Reset</button>


</form>
</head>
</html>
Output:

1.Enter Values of a and b

Prepared by:-Mr.Pramod Mane Page 16


Unit 4 Creating and Validating Forms SVERI
2.Clicked on ADD Button

2.Clicked on SUB Button

2.Clicked on Reset Button

Prepared by:-Mr.Pramod Mane Page 17


Unit 4 Creating and Validating Forms SVERI
4.3 working with multiple forms:
-A web page having many forms
-A form having multiple submit buttons

 Processing form data in PHP is significantly simpler than most other Web programming
languages
 This simplicity and ease of use makes it possible to do some fairly complex things with
forms,
 including handling multiple forms and multiple submit buttons in the same form.

A web page having many forms:-

 Multiple-page applications work in a "traditional way. Every change

 Example:- display the data or submit data back to server requests rendering a new page
from the server in the browser

 These applications are large, bigger than single page application because they need to be.
Due to the amount of content, these applications have many levels of User Interface (UI).

 Now it is possible to create multiple forms under a single web page to reduce the
parameter such as no page reloads, no extra wait time etc.

Program
<html>
<body>

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


<fieldset>
<legend> Form 1:</legend>
<h4>Email : <input type="text",name="email"/></h4>
<input type="submit" name="s1" value="Add to Mail List"/>
</fieldset>
</form>

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


<fieldset>
<legend> Form 2:</legend>
<h4>Email : <input type="text",name="email"/></h4>
<h4>Subject : <input type="text",name="subject"/></h4>
<h4>Write Message Here : <textarea name="message"></textarea></h4>
<input type="submit" name="s2" value="send email"/>
</fieldset>
</form>
</body>
</html>

Prepared by:-Mr.Pramod Mane Page 18


Unit 4 Creating and Validating Forms SVERI
Output:-

Clicked Add to Mail List Form 1 Called

Clicked send email List Form 2 Called

Prepared by:-Mr.Pramod Mane Page 19


Unit 4 Creating and Validating Forms SVERI

A form having multiple submit buttons:-

 First let we know, how to use multiple submit buttons in a HTML form and how PHP
handle it

 Usually a HTML form has only one submit button but there are situations when we might
need to use more than one submit buttons and PHP check which button has been pressed
and an action to be done according to the button pressed

 Having multiple submit buttons and handling them through PHP is just a matter of
checking the name of the button with the corresponding value of the button using
conditional statements
Program:-
button.php
<html>
<body>
<h4>How to call PHP function on the click of a Button ? </h4>
<?php

if(array_key_exists('button1', $_POST)) //if button1 or button2 click


{
button1(); //ADD
}
else if(array_key_exists('button2', $_POST)) //button2 button2
{
button2(); //Sub
}
function button1() //ADD
{
if(isset ($_POST['button1']))
{
$a=$_POST['a'];//10
$b=$_POST['b'];//20
$sum=$a+$b;
echo "Addition of $a and $b is:".$sum;
}
}
function button2() //Substractions
{
if(isset ($_POST['button2']))
{
$a=$_POST['a'];
$b=$_POST['b'];
$sub=$a-$b;
echo "Substractions of $a and $b is:".$sub;
}

Prepared by:-Mr.Pramod Mane Page 20


Unit 4 Creating and Validating Forms SVERI
}
?>

<form method="post">

Enter Value of a:-


<input type="number" name="a"/><br><br>

Enter Value of b:-


<input type="text" name="b"/><br><br>

<input type="submit" name="button1"class="button" value="ADD" />

<input type="submit" name="button2"class="button" value="SUB" />

<button type="reset" value="Reset">Reset</button>


</form>
</head>
</html>
Output:

1.Enter Values of a and b

2.Clicked on ADD Button

Prepared by:-Mr.Pramod Mane Page 21


Unit 4 Creating and Validating Forms SVERI
2.Clicked on SUB Button

2.Clicked on Reset Button

Prepared by:-Mr.Pramod Mane Page 22


Unit 4 Creating and Validating Forms SVERI

4.4 Web page validation

What is Validation ?
 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


Field Validation Rules

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

There are seven validation filters.


1. FILTER_VALIDATE_EMAIL -------to check valid email
2. FILTER_VALIDATE_URL -------to check valid website URL
3. FILTER_VALIDATE_BOOLEAN -------to check valid Boolean No
4. FILTER_VALIDATE_FLOAT ------to check valid Float No
5. FILTER_VALIDATE_INT -------to check valid Integer No
6. FILTER_VALIDATE_IP -------to check valid IP address
7. FILTER_VALIDATE_REGEXP -------to check valid Regular Expression

Prepared by:-Mr.Pramod Mane Page 23


Unit 4 Creating and Validating Forms SVERI
Program:-
Formvalidation.php
<html>
<head>
<style>
.error {color: #FF0000;}
.title {color: #FF1493;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

//if ($_SERVER["REQUEST_METHOD"] == "POST") //used for both GET and POST Method
if(isset($_POST['submit']))
{
if (empty($_POST["name"]))
{
$nameErr = "Name is required";

}
else
{
$name = ($_POST["name"]);
}

if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = ($_POST["email"]);
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) //Filiter
{
$emailErr="Invalid E-mail id";
}
}

if (empty($_POST["website"]))
{
$website = "";
}

Prepared by:-Mr.Pramod Mane Page 24


Unit 4 Creating and Validating Forms SVERI
else
{
$website = ($_POST["website"]);
}

if (empty($_POST["comment"]))
{
$comment = "";
}
else
{
$comment = ($_POST["comment"]);
}

if (empty($_POST["gender"]))
{
$genderErr = "Gender is required";
}
else
{
$gender = ($_POST["gender"]);
}
}

?>

<span class="title"><h2>Welcome to SPC College</h2></span>


<p><span class="error">* required field</span></p>

<form method="post" action="<?php ($_SERVER["PHP_SELF"]);?>">


Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>

E-mail: <input type="text" name="email">


<span class="error">* <?php echo $emailErr;?></span>
<br><br>

Website: <input type="text" name="website">


<span class="error"><?php echo $websiteErr;?></span>
<br><br>

Comment: <textarea name="comment" rows="5" cols="40"></textarea>


<br><br>
Gender:
<input type="radio" name="gender" value="female">Female

Prepared by:-Mr.Pramod Mane Page 25


Unit 4 Creating and Validating Forms SVERI
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Output:-

Prepared by:-Mr.Pramod Mane Page 26


Unit 4 Creating and Validating Forms SVERI
4.5 Cookies-
 Use of cookies
 Attributes of cookies
 Create cookies
 Modify cookies value
 Delete cookies

Use of Cookie
What is a Cookie?

 A cookie is often used to identify a user.

 A cookie is a small file that the server embeds on the user's computer.

 Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.

Types of cookies
The types of cookies are explained below:

1. Session Cookies

 Session Cookies also called a transient Cookies, a Cookies that is erased when we close
the Web browser

 The session Cookies is stored in temporary memory and is not retained after the browser
is closed.

 Session Cookies do not collect information from the computer

 Session Cookies are temporary means they are stored temporarily in memory and are
automatically removed when the browser close or the session ends

Prepared by:-Mr.Pramod Mane Page 27


Unit 4 Creating and Validating Forms SVERI

 Session Cookies expire at the end of the session.

 when we close our browser window, the session Cookies is deleted. This website only
use session Cookies

2. Persistent Cookies:

 Persistent Cookies do not expire at the end of the session. Persistent cookies also called a
permanent Cookies, or stored cookie.
 A cookie that is stored on the hard drive until it expires (persistent Cookies are set with
expiration dates) or until we delete the cookie.
 Persistent cookies are used to collect identifying information about the user, such as Web
surfing
 behavior or user preferences for a specific Web site

isset () function:
 To read data from a cookies, we first have to check if the cookie actually exists
 This is achieved by using isset() function
 $_COOKIE it stores an array of exciting cookies
Syntax

isset($_COOKIE[‘name_of_cookie’]);

if cookie is present then isset() function return true

Program:

<?php
if(!isset($_COOKIE[$cookie_name]))
{
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

Prepared by:-Mr.Pramod Mane Page 28


Unit 4 Creating and Validating Forms SVERI

Attributes of cookies
Create Cookies with PHP

 A cookie is created with the setcookie () function.

Syntax
setcookie (name, value, expire, path, domain, secure, httponly);

Parameter Description
name Required. Specifies the name of the cookie
value Optional. Specifies the value of the cookie
expire Optional. Specifies when the cookie expires. The value:
time()+86400*30, will set the cookie to expire in 30 days. If this
parameter is omitted or set to 0, the cookie will expire at the end of the
session (when the browser closes). Default is 0
path Optional. Specifies the server path of the cookie. If set to "/", the cookie
will be available within the entire domain. If set to "/php/", the cookie will
only be available within the php directory and all sub-directories of php.
The default value is the current directory that the cookie is being set in
domain Optional. Specifies the domain name of the cookie. To make the cookie
available on all sub domains of example.com, set domain to
"example.com". Setting it to www.example.com will make the cookie
only available in the www sub domain
secure Optional. Specifies whether or not the cookie should only be transmitted
over a secure HTTPS connection. TRUE indicates that the cookie will
only be set if a secure connection exists. Default is FALSE
httponly Optional. If set to TRUE the cookie will be accessible only through the
HTTP protocol (the cookie will not be accessible by scripting languages).
This setting can help to reduce identity theft through XSS attacks. Default
is FALSE

Prepared by:-Mr.Pramod Mane Page 29


Unit 4 Creating and Validating Forms SVERI

Create cookies
 To create cookie we use setcookie() function

Program
Createcookie.php
<?php
$cookie_name = "Pramod";
$cookie_value = "SPC"; //1 hr = 3600 sec so 24 hr=86400 sec
setcookie($cookie_name, $cookie_value, time() + (7200)); // 86400 = 1 day
?>

<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name]))
{
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Output:-

After Refresh the cookies are get set by setcookie()

Prepared by:-Mr.Pramod Mane Page 30


Unit 4 Creating and Validating Forms SVERI

Modify cookies value


 To Modify cookies just set the cookie using setcookie()function with new values

modifycookie.php
<?php
$cookie_name = "Pramod";
$cookie_value = "123456"; //1 hr = 3600 sec so 24 hr=86400 sec
setcookie($cookie_name, $cookie_value, time() + (7200)); // 86400 = 1 day
?>

<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name]))
{
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else
{
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Output:-

Prepared by:-Mr.Pramod Mane Page 31


Unit 4 Creating and Validating Forms SVERI

Delete cookies
 To Delete cookies just set the cookie using setcookie()function with an expiration date in
the past i.e time () - (7200)

deletecookie.php
<?php
//1 hr = 3600 sec so 24 hr=86400 sec
setcookie("Pramod",time() - (7200)); // set time as past value i.e -7200
?>

<html>
<body>

<?php

echo "cookies Pramod is deleted";


?>
</body>
</html>
Output:-

Prepared by:-Mr.Pramod Mane Page 32


Unit 4 Creating and Validating Forms SVERI

Where to see our created cookies information in Browser?

Prepared by:-Mr.Pramod Mane Page 33


Unit 4 Creating and Validating Forms SVERI
4.6 Session-
 Use of session
 Start session
 Get session variable
 Destroy session

Use of session:-
 PHP session is used to store and pass information from one page to another temporarily
(until user close the website).
 PHP session technique is widely used in shopping websites where we need to store and
pass cart information e.g. username, product code, product name, product price etc from
one page to another.
 PHP session creates unique user id for each browser to recognize the user and avoid
conflict between multiple browsers.

What is a PHP Session?


 When you work with an application, you open it, do some changes, and then you
close it. This is much like a Session.
 The computer knows who you are. It knows when you start the application and
when you end.
 But on the internet there is one problem: the web server does not know who you
are or what you do, because the HTTP address doesn't maintain state.
 Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc).
 By default, session variables last until the user closes the browser.

Prepared by:-Mr.Pramod Mane Page 34


Unit 4 Creating and Validating Forms SVERI

Start session:-
 A session is started with the session_start() function.
 Session variables are set with the PHP global variable: $_SESSION.
 The session_start() function must be the very first thing in your document.
 Before any HTML tags.
Program:-
Startsession.php
<?php
// Start the session
session_start();
?>

<html>
<body>

<?php
// Set session variables
$_SESSION["name"] = "pramod";
$_SESSION["rno"] = 10;
echo "Session variables are set.";
?>

</body>
</html>

Output:-

Prepared by:-Mr.Pramod Mane Page 35


Unit 4 Creating and Validating Forms SVERI

Get session variable:-


 we create another page called "getsession.php". From this page, we will access the
session information we set on the first page ("startsession.php").
 Notice that session variables are not passed individually to each new page, instead they
are retrieved from the session we open at the beginning of each page (session_start()).
 Also notice that all session variable values are stored in the global $_SESSION variable:

Program:
getsession.php
<?php
// Start the session
session_start();
?>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Your Name is " . $_SESSION["name"] . "<br>"; //pramod
echo "Your Roll no is " . $_SESSION["rno"]; // 10

?>

</body>
</html>

Output:-

Prepared by:-Mr.Pramod Mane Page 36


Unit 4 Creating and Validating Forms SVERI

Destroy session:-
 To remove all global session variables and destroy the session use
a. session_unset()
b. session_destroy()

Program:
destroysession.php
<?php
// Start the session
session_start();
?>
<html>
<body>

<?php
session_unset();// remove all session variables

session_destroy();// destroy the session

echo "Session are destroyed";


?>

</body>
</html>

Output:-

Prepared by:-Mr.Pramod Mane Page 37


Unit 4 Creating and Validating Forms SVERI

Difference table between Cookies and Session

Session Cookies

A session stores the variables and their values Cookies are stored on the user's computer as a
within a file in a temporary directory on the server. text file.

The session ends when the user logout from the Cookies end on the lifetime set by the user.
application or closes his web browser.

It can store an unlimited amount of data. It can store only limited data.

We can store as much data as we want within a The maximum size of the browser's cookies is
session, but there is a maximum memory limit, 4 KB.
which a script can use at one time, and it is 128
MB.

We need to call the session_start() function to start We don't need to call a function to start a
the session. cookie as it is stored within the local computer.

In PHP, to set a session data, the $_SESSION In PHP, to get the data from cookies, the
global variable is used. $_COOKIE global variable is used.

In PHP, to destroy or remove the data stored We can set an expiration date to delete the
within a session, we can use the session_destroy() cookie's data. It will automatically delete the
function, and to unset a specific variable, we can data at that specific time. There is no particular
use the unset() function. function to remove the data.

Sessions are more secured compared to cookies, as Cookies are not secure, as data is stored in a
they save data in encrypted form. text file, and if any unauthorized user gets
access to our system, he can temper the data.

Prepared by:-Mr.Pramod Mane Page 38


Unit 4 Creating and Validating Forms SVERI

4.7 Sending E-mail


 To send e-mail using PHP we must make some changes to following 2 files

1.sendmail.ini

2.php.ini

1.sendmail.ini
****sendmail.ini****

Go to Path of sendmail.ini:- C:\xampp\sendmail

[sendmail]

smtp_server=smtp.gmail.com

smtp_port=465

smtp_ssl=ssl

auth_username= write sender Gmail id

auth_password= write Gmail password

force_sender= write sender Gmail id

2.php.ini
****php.ini****

Go to Path of php.ini:- C:\xampp\php

[mail function]

; For Win32 only.

sendmail_from = write sender Gmail id

; http://php.net/sendmail-path

sendmail_path ="C:\xampp\sendmail/sendmail.exe -t"

Note-Remove ; from all above highlighted lines in color

Prepared by:-Mr.Pramod Mane Page 39


Unit 4 Creating and Validating Forms SVERI

Sending plain text email


 PHP makes use of mail() function to send an email.

 This function requires three mandatory arguments that specify the

 recipient's email address,

 the subject of the the message

 the actual message additionally there are other two optional parameters.

Syntax:-

mail (to,subject,message,headers, parameters);

Parameter Description

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

Prepared by:-Mr.Pramod Mane Page 40


Unit 4 Creating and Validating Forms SVERI

Program:-
<?php
$to = "[email protected]";
$subject = "Welcome to SPC";
$message = "Computer Department ";
$headers="[email protected]";

$test = mail ($to,$subject,$message,$headers);

if( $test == true )


{
echo "Message sent successfully to ".$to;
}
else
{
echo "Message could not be sent...";
}
?>
Output:-

Prepared by:-Mr.Pramod Mane Page 41

You might also like