Unit 4
Unit 4
Unit 4
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
There are two ways the browser client can send information to the web server.
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.
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.
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.
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.
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.
Information sent from a form with the GET method is visible to everyone (all variable
names and values are displayed in the URL).
the variables are displayed in the URL, it is possible to bookmark the page.
Note: GET should NEVER be used for sending passwords or other sensitive information!
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)
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.
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">
</form>
</body>
</html>
Output:-
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">
</form>
</body>
</html>
Output:-
Server Role:-
PHP is server-side scripting language
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 .
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
<form action="textarea.php"method="GET">
</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:-
radiobutton.php
<?php
$c=$_GET['color'];
if (($c!=null))
{
echo "You Selected favorite color is <b>".$_GET ['color']."</b>";
}
?>
Output:-
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">
</br></br>
foreach($_GET['check_list']as $selected)
{
echo "<p>".$selected."</p>";
//echo $selected ;
}
}
else
{
echo "<b>Please select at lest one option.</b>";
}
}
?>
Output:-
</select>
</br></br>
<input type="submit" name="s1" value="Submit"/>
</form>
</body>
</html>
Output:-
<?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:-
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" />
<form method="post">
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.
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>
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
<form method="post">
What is Validation ?
Validation means check the input submitted by the user.
Server Side Validation − After submitted by data, The data has sent to a server and
perform validation checks in server machine.
<?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 = "";
}
if (empty($_POST["comment"]))
{
$comment = "";
}
else
{
$comment = ($_POST["comment"]);
}
if (empty($_POST["gender"]))
{
$genderErr = "Gender is required";
}
else
{
$gender = ($_POST["gender"]);
}
}
?>
<?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:-
Use of Cookie
What is a Cookie?
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 are temporary means they are stored temporarily in memory and are
automatically removed when the browser close or the session ends
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’]);
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];
}
?>
Attributes of cookies
Create Cookies with PHP
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
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:-
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:-
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
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.
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:-
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:-
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
</body>
</html>
Output:-
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.
1.sendmail.ini
2.php.ini
1.sendmail.ini
****sendmail.ini****
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=465
smtp_ssl=ssl
2.php.ini
****php.ini****
[mail function]
; http://php.net/sendmail-path
the actual message additionally there are other two optional parameters.
Syntax:-
Parameter Description
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)
Program:-
<?php
$to = "[email protected]";
$subject = "Welcome to SPC";
$message = "Computer Department ";
$headers="[email protected]";