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

PHP_CH_04

This document provides an overview of creating and validating forms in PHP, detailing the GET and POST methods for sending data to a server. It explains the advantages and disadvantages of each method, along with examples of HTML forms and PHP scripts for processing the data. Additionally, it covers various form elements such as text fields, checkboxes, and select menus, demonstrating how to implement them in web applications.
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)
6 views

PHP_CH_04

This document provides an overview of creating and validating forms in PHP, detailing the GET and POST methods for sending data to a server. It explains the advantages and disadvantages of each method, along with examples of HTML forms and PHP scripts for processing the data. Additionally, it covers various form elements such as text fields, checkboxes, and select menus, demonstrating how to implement them in web applications.
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/ 26

UNIT 4

Creating and Validating Forms


Creating a Web page using GUI Components

Get and Post Methods in PHP


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

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.

For Example:if, and JVM


http://localhost/ test.php?Username=Arrow&BloodGroup=B
Username and BloodGroup are the GET parameters and Arrow and B are their values
Note that only a limited amount of information can be sent using the GET method.
Example
The below code will display an HTML form containing two input fields and a submit button.
In this HTML form, we used the method = "get" to submit the form data.

File1: test1.html
<html>
<body>
<form name="form1" action="gettest.php" method="get">
Enter Name: <br> <input type="text" name="Username"> <br><br>
Enter Blood Group:<br> <input type="text" name="BloodGroup"> <br><br>
<input type="submit" name="submit">
</form>
</body>
</html>

Output:

Open this file in localhost.


Create gettest.php file, which will accept the data sent by HTML form.

File2: gettest.php
<?php
//print_r($_GET);
echo "<br>";
echo "UserName is ".$_GET['Username'];
echo "<br>";
echo "Blood Group is ".$_GET['BloodGroup'];
?>

When the user will click on Submit button after filling the form, the URL sent to the server could look
something like this:

http://localhost/practicals/test.php?Username=Arrow&BloodGroup=B&submit=Submit

Output: Harry

UserName is Arrow
Blood Group is B Y
Advantages of GET method (method = "get")
o You can bookmark the page with the specific query string because the data sent by the GET
method is displayed in URL.
o GET requests can be cached.
o GET requests are always remained in the browser history.

Disadvantages of GET Method


o The GET method should not be used while sending any sensitive information like username and
password, because it shows them in the URL.
o A limited amount of data can be sent using method = "get". This limit should not exceed 2048
characters.
o The GET method cannot be used to send binary data (such as images or word documents) to the
server.

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 "post" method is more secure than the "get" method because the information sent from an HTML
form using the POST method is not visible to anyone.
So it is not possible to bokmark page with specific query.
Example
The below code will display an HTML form containing two input fields and a submit button.
In this HTML form, we used the method = "post" to submit the form data.

File 1 : test2.html
<!DOCTYPE html>
<html>
<body>
<form name="form2" action="test2.php" method="post">
Enter Name: <br> <input type="text" name="Username"><br><br>
Enter Blood Group:<br> <input type="text" name="BloodGroup"><br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Now create test2.php file to accept the data sent by HTML form.

File: test2.php
<?php
//print_r($_POST);
echo "<br>";
echo "UserName is ".$_POST['Username'];
echo "<br>";
echo "Blood Group is ".$_POST['BloodGroup'];
?>

When the user will click on Submit button after filling the form, the URL sent to the server could look
something like this:

http://localhost /test2.php

Output:
UserName is Akshay
Blood Group is B+

Advantages of POST method (method = "post")


o The POST method is useful for sending any sensitive information because the information sent
using the POST method is not visible to anyone.
o There is no limitation on size of data to be sent using the POST Method. You can send a large
amount of information using this method.
o Binary and ASCII data can also be sent using the POST method.
o Data security depends on the HTTP protocol because the information sent using the POST method
goes through the HTTP header. By using secure HTTP, you can ensure that your data is safe.

Disadvantages of POST Method


o POST requests do not cache.
o POST requests never remain in the browser history.
o It is not possible to bookmark the page because the variables are not displayed in URL.
Compare GET vs POST
The following table compares the two HTTP methods: GET and POST.

GET POST

BACK Harmless Data will be re-submitted (the


button/Reload browser should alert the user that
the data are about to be re-
submitted)

Bookmarked Can be bookmarked Cannot be bookmarked

Cached Can be cached Not cached

Encoding type application/x-www-form-urlencoded application/x-www-form-


urlencoded or multipart/form-
data. Use multipart encoding for
binary data

History Parameters remain in browser Parameters are not saved in


history browser history

Restrictions on Yes, when sending data, the GET No restrictions


data length method adds the data to the URL; and
the length of a URL is limited
(maximum URL length is 2048
characters)

Restrictions on Only ASCII characters allowed No restrictions. Binary data is also


data type allowed

Security GET is less secure compared to POST POST is a little safer than GET
because data sent is part of the URL because the parameters are not
stored in browser history or in
Never use GET when sending web server logs
passwords or other sensitive
information!

Visibility Data is visible to everyone in the URL Data is not displayed in the URL
Server Role

How PHP Engine Outputs Content


When PHP interpreter reads a file, it only processes lines between <?php and ?> tags. It outputs rest of
the lines without any processing.

For an example, in welcome.php, PHP interpreter outputs all the HTML content till <?php tag without
any processing. Then based on the time of the day it adds Good Morning! or Welcome! to the output.
Then from </h1> tag, it outputs rest of the lines without processing. Web server collects all these
outputs and sends to the client who made the request.

PHP Script Life Cycle

We always start with a browser making a request for a web page. This request is going to hit the web
server. The web server will then analyze it and determine what to do with it.

If the web server determines that the request is for a PHP file (often index.php ), it’ll pass that file to the
PHP interpreter. The PHP interpreter will read the PHP file, parse it (and other included files) and then
execute it. Once the PHP interpreter finishes executing the PHP file, it’ll return an output. The web server
will take that output and send it back as a response to the browser.
PHP Form Elements

Element Description

input type="checkbox" A checkbox that lets users select multiple options.

input type="file" A text box plus a button that opens a file selection dialog.

input type="hidden" A hidden form element.

input type="password" A password text box.

input type="radio" A radio button.

input type="reset" A button to clear the form.

input type="submit" A button to submit the form.

input type="text" A text box.

option An option in a SELECT element.

select A listbox; can also be a drop-down list box.

textarea Multiline text box.

Form is created with the get method. This means that the form field names and values will be sent to the
server in the URL. Meanwhile, the empty action attribute tells the browser to send the form back to the
same page.
Field names and field values as being similar to the keys and values of an associative array.
Most controls are also given an associated label element. This text describes the field to the users. Each
label is associated with its control using its for attribute, which matches the corresponding id attribute in
the control element.
PHP Form TextField
A text input field allows the user to enter a single line of text.
You can optionally prefill the field with an initial value using the value attribute . To leave it blank, specify
an empty string for the value attribute, or leave the attribute out altogether.

<html>
<body>
<form action="gettest.php" method="get">
<label for="textField">A text input field</label>
<input type="text" name="user" id="textField" value="" />
<input type="submit" value="hit it!" />
</form>
</body>
</html>
Name the following script as gettest.php and put it into the same folder as above index.htm file. It accepts
the value from the text field by using field name user.

<?php
print "Welcome <b>" . $_GET ['user'] . "</b><br/>";
?>

PHP Form Textarea


A Textarea field is similar to a text input field, but it allows the user to enter multiple lines of text.
The rows attribute specifies the visible number of lines in a text area.
The cols attribute specifies the visible width of a text area
<label for="textAreaField">A text area field</label>
<textarea name="textAreaField" id="textAreaField" rows="4" cols="50"></textarea>
Example: test1.html

<html>
<body>
<form action="index.php" method="get">
<textarea name="address" rows="5" cols="40"></textarea>
<input type="submit" value="hit it!" />
</form>
</body>
</html>

Name the following script as index.php. It reads the value from the textarea from the form above.

<?php
print "Your address is: <br/><b>" . $_GET ['address'] . "</b>";
?>
PHP Form CheckBox
A checkbox field is a simple toggle button. It can be either on or off.

The HTML <checkbox> tag is used to define the square boxes. It is a form element which allows users to
select one or more options from the given options.

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.

<label for="checkboxField">A checkbox field</label>


<input type="checkbox" name="checkboxField" id="checkboxField" value="yes" />
You can preselect a checkbox by adding the attribute checked="checked" to the input tag:
<input type="checkbox" checked="checked" ... />.
By creating multiple checkbox fields with the same name attribute, you can allow the user to select
multiple values for the same field.

Example

The following script is for index.html. It has several checkboxes.


<html>
<body>
<form action ="Demo.php" method="GET">
<ul>
<li><input type ="checkbox" name ="Fries" value ="11.00">Fries</li>
<li><input type ="checkbox" name ="Soda" value ="12.85">Soda</li>
<li><input type ="checkbox" name ="Shake" value ="1.30">Shake</li>
<li><input type ="checkbox" name ="Ketchup" value =".05">Ketchup</li>
</ul>
<input type ="submit">
</form>
</body>
</html>
Name the following script as index.php.

<?PHP
$total = 0;

if (isset($_GET["Fries"]))
{
print ("You chose Fries <br>");
print "Fries:" .$_GET["Fries"] ."<br/>";
$total = $total + $_GET["Fries"];
}

if (isset($_GET["Soda"]))
{
print ("You chose Soda <br>");
print "Soda:" .$_GET["Soda"]."<br/>";
$total = $total + $_GET["Soda"];
}

if (isset($_GET["Shake"]))
{
print ("You chose Shake <br>");
print "Shake:" .$_GET["Shake"]."<br/>";
$total = $total + $_GET["Shake"];
}

if (isset($_GET["Ketchup"]))
{
print ("You chose Ketchup <br>");
print "Ketchup" .$_GET["Ketchup"]."<br/>";
$total = $total + $_GET["Ketchup"];
}

echo "The total cost is ".$total;

?>
PHP Form Select
Form Select as Pull-down menu
A pull-down menu allows users to choose a single item from a predefined list of options. The size
attribute's value of 1 tells the browser that you want the list to be in a pull-down menu format.

Within the select element, you create an option element for each of your options.
Place the option label between the <option> ... </option> tags.
Each option element can have an optional value attribute, which is the value sent to the server if that
option is selected.
If you don't include a value attribute, the text between the <option> ... </option> tags is sent instead.

You can preselect an option in any type of select element by adding the attribute selected="selected" to
the relevant <option> tag - for example: <option value="option1" selected="selected">.

<label for="pullDownMenu">A pull-down menu</label>


<select name="pullDownMenu" id="pullDownMenu" size="1">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

Example:-
test1.html
<html>
<body>
<form action="Demo.php" method="post">
<select name="products">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Scorpio">Scorpio</option>
<option value="Mercedeze">Mercedeze</option>
</select>
<input type="submit" value="submit" >
</form>
</body>
</html>

Demo.php
<?php
echo "Your product choice is:";
echo $_POST["products"];
?>
Form Select as List Box
A list box works like a pull-down menu, except that it displays several options at once.
To turn a pull-down menu into a list box, change the size attribute from 1 to the number of options to
display at once:

<label for="listBox">A list box</label>


<select name="listBox" id="listBox" size="3">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

Form Select as multi-select list box


A multi-select list box allows the user to select multiple items at once by holding down Ctrl or Command
key.
To turn a normal list box into a multi-select box, add the attribute multiple with a value of "multiple" to
the select element.
If the user selects more than one option, all the selected values are sent to the server.
But to send all elements, you must make the name attribute of select as array.

<label for="multiListBox">A multi-select list box</label>


<select name="multiListBox[ ]" id="multiListBox" size="3" multiple="multiple">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

Example
Name the following script as test1.php. It has a multi-select list box.

<html>
<body>
<form action="Demo.php" method="post">
<select name="products[]" multiple="multiple">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Scorpio">Scorpio</option>
<option value="Mercedeze">Mercedeze</option>
</select>
<input type="submit" value="submit" >
</form>
</body>
</html>
The following script is for Demo.php.
<?php
if (isset ( $_POST ["products"] ))
{
echo "Your product choices are:";
foreach ( $_POST ["products"] as $value )
{
echo "<li>$value</li>";
}
}
?>

PHP Form RadioButton


The radio buttons are for single choice from multiple options. All radio buttons in the group have the
same name attribute.

Only one button can be selected per group. As with checkboxes, use the value attribute to store the value
that is sent to the server if the button is selected.

The value attribute is mandatory for checkboxes and radio buttons, and optional for other field types.

<input type="radio" name="radioButtonField" id="radioButtonField1" value="radio1" />


<input type="radio" name="radioButtonField" id="radioButtonField2" value="radio2" />
You can preselect a radio button using the same technique as for preselecting checkboxes.

Example
The following script is for index.htm. It has a group of radio buttons.

<html>
<body>
<form action="Demo1.php" method="post">
<b>Please select your favorite color wine:</b> <br>
<input type="radio" name="color" value="white"> White <br>
<input type="radio" name="color" value="rose"> Rose <br>
<input type="radio" name="color" value="red"> Red <br>
<input type="submit" value="Submit This Form">
</form>
</body>
</html>

The following script is for index.php. It reads the data from the form above.
<?php
$color = $_POST['color'];
if( ( $color != null ) )
{
echo "$color is nice color";
}
?>

PHP Form Hidden Field


A hidden field is not displayed on the page.
It simply stores the text value specified in the value attribute.
Hidden fields are great for passing additional information from the form to the server.

<label for="hiddenField">A hidden field</label>


<input type="hidden" name="hiddenField" id="hiddenField" value="" />

Example
The following form uses hidden field to store user id.

<html>
<body>
<form method="post" action= "Demo1.php">
<input type="hidden" name="user_id" value="101" />
<input type="submit" value="submit" />
</form>
</body>
</html>

The following script is for index.php. It reads the data from the form above.

<?php
if (isset($_POST["user_id"]))
{
echo "<p>User ID: " .$_POST["user_id"];
}
?>
Working with Multiple Forms

A Web Page having Multiple Forms


A web page having multiple forms can be processed in two types:

o Posting each form to different PHP Script file for processing

Multiple functionalities can be provided in a single web page by providing multiple forms in a web page
having different functionality.
Each form on this web page will be given a separate name that will uniquely identify the form in web
page with multiple forms.
Data from each form should be given to separate PHP script file for processing by specifying PHP script
filename in the action attribute of the forms.
Each PHP Script should be written in such a fashion that will handle all the data coming from that form.
Disadvantage of this method is that we have to write separate PHP script for each form, which creates
extra files for handing.

For Example, a Web page multiformdemo.html has two forms, one for sending mail information and
another for sending mobile number information, each form is having its own PHP script written to
handle its own form elements on the server, on clicking submit button of each form data is sent to its
corresponding PHP script which handles the request and generates response for user.

Example: test1.php
<html>
<head>
<title> Multiple Form Demo</title>
</head>
<body>
<form name="mailform" method="post" action="emaildata.php">
<input type="text" name="email" id="email" >
<input type="submit" name="mail_submit" value="Send Mail Information"/>
</form>
<form name="mobileform" method="post" action="mobiledata.php">
<input type="text" name="mobileno" id="mobileno">
<input type="submit" name="mobile_submit" value="Send Contact Information">
</form>
</body>
</html>
emaildata.php
<?php
if($_SERVER['REQUEST_METHOD'] =='POST') //optional
{
if (!empty($_POST["mail_submit"]))
{
echo "Your mail id is:".$_POST["email"];
}
}
?>

mobiledata.php
<?php
if($_SERVER['REQUEST_METHOD'] =='POST')
{
if (!empty($_POST["mobile_submit"]) )
{
echo "Your mobile number is:".$_POST["mobileno"];
}
}
?>

o Posting all form to single PHP script file for processing

Multiple functionalities can be provided in a single web page by providing multiple forms in a web page
having different functionality.
Each form on this web page will be given a separate name that will uniquely identify the form in web
page with multiple forms.
Data from each form should be given to a single PHP script file for processing by specifying PHP script
filename in the action attribute of the forms.
Each PHP Script should be written in such a fashion that will handle all the data coming from multiple
forms.
Data from multiple forms can be identified by it submit button and the processing each form will be
written with help of if, else and else if conditional statements.
Advantage of this method is that we have to write a single PHP script for processing of all forms, which
saves time in the creation and handling of extra files..
For Example, a Web page multiformdemo.html has two forms, one for sending mail information and
another for sending mobile number information, both form are having a single PHP script written to
handle data of all forms on the server, by clicking submit button of each form data is sent to its PHP script
which identify the form by its submit button based on that it fetches the request and a generates a
response for the user.
Example: test1.php
<html>
<head>
<title> Multiple Form Demo</title>
</head>
<body>
<form></form>
<form name="mailform" method="post" action="multiformdemo.php">
<input type="text" name="email" id="email" >
<input type="submit" name="mail_submit" value="Send Mail Information"/>
</form>
<form name="mobileform" method="post" action="multiformdemo.php">
<input type="text" name="mobileno" id="mobileno">
<input type="submit" name="mobile_submit" value="Send Contact Information">
</form>
</body>
</html>

multiformdemo.php
<?php
if($_SERVER['REQUEST_METHOD'] =='POST')
{
if (!empty($_POST["mail_submit"]))
{
echo "Your mail id is:".$_POST["email"];
}

if (!empty($_POST["mobile_submit"]) )
{
echo "Your mobile number is:".$_POST["mobileno"];
}
}
?>
A Form having Multiple Submit Buttons
Multiple operations can be provided on a single form by providing a different buttons for different
operation.
Based on which button is clicked, data in the form is processed differently for the operations mentioned
on that button.
Single PHP Script is sufficient to handle all the operations mentioned on the buttons in the form,
PHP Script will identify the button which is being clicked and will carry out the operations according to it.
Identification of the button is done by its name on the server and corresponding operation is called with
the help of if, else and else if conditional statements.
For Example a Web page multibuttondemo.html is having two text fields for accepting two numbers from
user and two submit buttons representing Add and Subtract operation is forms, on clicking each button a
corresponding operation mention in PHP script phpmultibuttondemo.php on the server will be called.

Example 1: multibuttondemo.html
<html>
<head>
<title> Multiple Submit Button </title>
<head>
<body>
<form name="mailform" method="post" action = "multibutton.php">
<input type="text" name ="no1" id= "no1"/>
<input type="text" name="no2" id="no2"/>
<input type="submit" name="Addition" value="Add"/>
<input type="submit" name="Subtraction" value="Subtract"/>
</form>
</body>
</html>

multibutton.php
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
if (!empty($_POST['Addition']))
{
echo "Adition of these two numbers is =".((int)$_POST['no1'] + (int) $_POST['no2']);
}
else if (!empty($_POST['Subtraction']))
{
echo "Subtraction of these two numbers is ".((int)$_POST['no1'] - (int)$_POST['no2']);
}
}
?>
Superglobals:

Superglobals are a type of variables that are available from any part of your code. Some are well known
like POST and GET that are used to pass form values and COOKIE and SESSION that are used to store
specific information for a later use.
Here are all the superglobals that are all available for you to use from within your functions, classes, file
or anywhere else, without any other requirements on your behalf.
 $_SERVER - An array containing information such as headers, paths, and script locations.
The entries in this array are created by the web server.
 $_REQUEST - An associative array that by default contains the contents
of $_GET, $_POST and $_COOKIE.
 $_POST - An associative array of variables passed to the current script via the HTTP POST method
 $_GET - An associative array of variables passed to the current script via the URL parameters
(query string).
 $_COOKIE - An associative array of variables passed to the current script via HTTP Cookies..
 $_SESSION - An associative array containing session variables available to the current script.
 $_FILES - An associative array of items uploaded to the current script via the HTTP POST
method.
 $GLOBALS - An associative array containing references to all variables which are currently
defined in the global scope of the script. The variable names are the keys of the array.
 $_ENV - An associative array of variables passed to the current script via the environment
method.
 $http_response_header - is similar to the get_headers() function. When using the HTTP
wrapper, $http_response_header will be populated with the HTTP response headers.
$http_response_header will be created in the local scope.
 $argc - The number of arguments passed to script
 $argv - Array of arguments passed to script
Cookies
A cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer.
Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received at the
server side.

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

Session Cookie: Session cookies is a cookie that remains in temporary memory only while user is
reading and navigating the web site. This type of cookies are temporary and are expire as soon as the
session ends or the browser is closed.
Persistent Cookie: A persistent cookie is a cookie that is assigned an expiration date.
A persistent cookie is written to the computer's hard disk and remains there until the
expiration date has been reached; then it is deleted.

Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The
setcookie() function needs to be called prior to any output generated by the script otherwise
the cookie will not be set.

Syntax :
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which are:

1. Name: It is used to set the name of the cookie.


2. Value: It is used to set the value of the cookie.
3. Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
4. Path: It is used to specify the path on the server for which the cookie will be available. Used to set a
web URL in the cookie. If set, the cookie will be accessible only from that URL.
5. Domain: It is used to specify the domain for which the cookie is available . For example, if you set
the domain value as www.arrow.com, then the cookie will be inaccessible from blog.arrow.com.
6. Security: If you set this to 1, then the cookie will be available and sent only over HTTPS connection.
Creating Cookies:
Creating a cookie named user and assigning the value Arrow to it. The cookie will expire after 30 days
(86400 * 30).

<?php
$cookie_name = "user";
$cookie_value = "Arrow";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30)); // 86400 = 1 day
?>
Note: Only the name argument in the setcookie() function is mandatory.

Checking Whether a Cookie Is Set Or Not:


It is always advisable to check whether a cookie is set or not before accessing its value.
Therefore to check whether a cookie is set or not, the PHP isset() function is used.
To check whether a cookie “user” is set or not, the isset() function is executed as follows:

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

Output:
Cookie user is set!
Value is: Arrow

Accessing Cookie Values: For accessing a cookie value, the PHP $_COOKIE superglobal
variable is used. It is an associative array that contains a record of all the cookies values sent by
the browser in the current request. The records are stored as a list where cookie name is used
as the key.
To access a cookie, the following code can be executed:

$value=$_COOKIE[$cookie_name ];//returns cookie value


Modify a cookie value
To modify a value in a created cookie, use the setcookie() function again
<?php
$cookie_name = "user";
$cookie_value = "Akshay";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30)); // 86400 = 1 day
?>

Deleting Cookies: The setcookie() function can be used to delete a cookie.


For deleting a cookie, the setcookie() function is called by passing the cookie name and other
arguments but this time, the expiration date is required to be set in the past.
To delete a cookie named “User”, the following code can be executed:

setcookie("User", "", time() - 3600);

Important Points
If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the
session i.e. when the browser closes.
The same path, domain, and other arguments should be passed that were used to create the
cookie in order to ensure that the correct cookie is deleted.
PHP Sessions

Although you can store data using cookies but it has some security issues. Since cookies are
stored on user's computer it is possible for an attacker to easily modify a cookie content to insert
potentially harmful data in your application that might break your application.

Also every time the browser requests a URL to the server, all the cookie data for a website is
automatically sent to the server within the request. It means if you have stored 5 cookies on
user's system, each having 4KB in size, the browser needs to upload 20KB of data each time the
user views a page, which can affect your site's performance.

You can solve both of these issues by using the PHP session. A PHP session stores data on the
server rather than user's computer. In a session based environment, every user is identified
through a unique number called session identifier or SID. This unique session ID is used to link
each user with their own information on the server like emails, posts, etc.

Tip: The session IDs are randomly generated by the PHP engine which is almost impossible to
guess. Furthermore, because the session data is stored on the server, it doesn't have to be sent
with every browser request.

Starting a PHP Session


Before you can store any information in session variables, you must first start up the session. To
begin a new session, simply call the PHP session_start() function. It will create a new session and
generate a unique session ID for the user.
The PHP code in the example below simply starts a new session.
Example
<?php
// Starting session
session_start();
?>

The session_start() function first checks to see if a session already exists by looking for the
presence of a session ID. If it finds one, i.e. if the session is already started, it sets up the session
variables and if doesn't, it starts a new session by creating a new session ID.

Note: The session_start() function must be the very first thing in your document before any
HTML tags.
Storing and Accessing Session Data
You can store all your session data as key-value pairs in the $_SESSION[] superglobal array. The stored
data can be accessed during lifetime of a session.
Now, let's create a new page called "demo1.php". In this page, we start a new PHP session and set some
session variables:
Example
<?php
// Starting session
session_start();
// Storing session data
$_SESSION["firstname"] = "Arrow";
$_SESSION["lastname"] = "Academy";
?>

Next, we create another page called "demo2.php". From this page, we will access the session information
we set on the first page ("demo1.php")
To access the session data we already set, simply recreate the session by calling session_start() and then
pass the corresponding key to the $_SESSION associative array.

Example
<?php
// Starting session
session_start();
// Accessing session data
echo 'Hi, ' . $_SESSION["firstname"] . ' ' . $_SESSION["lastname"];
?>
The PHP code in the example above produce the following output.
Hi, Arrow Academy

Note: To access the session data in the same page there is no need to recreate the session since it has
been already started on the top of the page.

Another way to show all the session variable values for a user session is to run the following code:
<?php
session_start();
print_r($_SESSION);
?>
Destroying a Session
To remove all global session variables, use session_unset().
However, to destroy a session completely, simply call the session_destroy() function. This function does
not need any argument and a single call destroys all the session data.

Example

<?php
session_start();
?>

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

// destroy the session


session_destroy();
?>

Note: Before destroying a session with the session_destroy() function, you need to first recreate the
session environment if it is not already there using the session_start() function, so that there is
something to destroy.

PHP Send Emails


The PHP mail() Function

Sending email messages are very common for a web application, for example, sending welcome
email when a user create an account on your website, sending newsletters to your registered
users, or getting user feedback or comment through website's contact form, and so on.

You can use the PHP built-in mail() function for creating and sending email messages to one or
more recipients dynamically from your PHP application either in a plain-text form or formatted
HTML.

The basic syntax of this function can be given with:

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


The following table summarizes the parameters of this function.

Parameter Description

Required — The following parameters are required

to The recipient's email address.

subject Subject of the email to be sent. This parameter i.e. the subject line cannot
contain any newline character (\n).
message Defines the message to be sent. Each line should be separated with a line
feed-LF (\n). Lines should not exceed 70 characters.
Optional — The following parameters are optional

headers This is typically used to add extra headers such as "From", "Cc", "Bcc". The
additional headers should be separated with a carriage return plus a line
feed-CRLF (\r\n).
parameters Used to pass additional parameters.

Sending Plain Text Emails


The simplest way to send an email with PHP is to send a text email. In the example below we first
declare the variables — recipient's email address, subject line and message body — then we pass
these variables to the mail() function to send the email.

Example
<?php
$to = '[email protected]';
$subject = ‘Interview Call';
$message = 'Hi, Your Interview is scheduled tomorrow at 9:00 am';
$from = '[email protected]';

// Sending email
if(mail($to, $subject, $message, $from))
{
echo 'Your mail has been sent successfully.';
}
else
{
echo 'Unable to send email. Please try again.';
}
?>

You might also like