PHP_CH_04
PHP_CH_04
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.
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:
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.
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+
GET POST
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
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.
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="file" A text box plus a button that opens a file selection dialog.
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/>";
?>
<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.
Example
<?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"];
}
?>
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">.
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:
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>";
}
}
?>
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.
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";
}
?>
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
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"];
}
}
?>
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:
<?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.
<?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:
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.
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();
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.
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.
Parameter Description
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.
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.';
}
?>