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

WBP Topic 4 Notes

The document discusses creating and validating forms in PHP using HTML, focusing on the use of superglobals $_GET and $_POST to collect form data. It explains the differences between GET and POST methods, their appropriate use cases, and includes examples of various form controls such as text fields, radio buttons, checkboxes, and hidden inputs. Additionally, it covers the $_SERVER['PHP_SELF'] variable for form handling and emphasizes the importance of validating user input to prevent malicious code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

WBP Topic 4 Notes

The document discusses creating and validating forms in PHP using HTML, focusing on the use of superglobals $_GET and $_POST to collect form data. It explains the differences between GET and POST methods, their appropriate use cases, and includes examples of various form controls such as text fields, radio buttons, checkboxes, and hidden inputs. Additionally, it covers the $_SERVER['PHP_SELF'] variable for form handling and emphasizes the importance of validating user input to prevent malicious code.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

WBP

Topic 4

Creating and Validating Forms


Browser Role-GET and POST methods
The PHP superglobals $_GET and $_POST are used to collect form-data.

PHP - A Simple HTML Form


The example below displays a simple HTML form with two input fields and a
submit button:

<html>
<body>

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


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 1


WBP

The output could be something like this:

Welcome John
Your email address is [email protected]

The same result could also be achieved using the HTTP GET method:

Example
<html>
<body>

<form action="welcome_get.php" method="get">


Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

and "welcome_get.php" looks like this:

<html>
<body>

Welcome <?php echo $_GET["name"]; ?><br>


Your email address is: <?php echo $_GET["email"]; ?>

</body>
</html>

The code above is quite simple. However, the most important thing is missing.
You need to validate form data to protect your script from malicious code.

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 superglobals,
which means that they are always accessible, regardless of scope - and you can

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 2


WBP

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 limitation is about 2000 characters.
However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.

GET may be used for sending non-sensitive data.

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

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) and has 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.

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 3


WBP

What is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename


of the currently executing script.

So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page
itself, instead of jumping to a different page. This way, the user will get error
messages on the same page as the form.

<html>

<body>

<form action="<?php echo $_SERVER['PHP_SELF'];?>"


method="POST">

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

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

<input type="submit" name="submit">

</form>

<?php

if(isset($_POST["submit"]))

echo $_POST['name']."<br>";

echo $_POST['email'];

?>

</body>

</html>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 4


WBP

PHP Form Handling


When we develop a website or a web application, we often have to
create forms to take input from users, like a Login form or
a Registration form.

Creating a form on the webpage is accomplished using HTML, while


PHP serves as a transport for those values from the webpage to the
server and then in further processing those values.

PHP provides two superglobals $_GET and $_POST for collecting form-
data for processing.

Understanding How HTML Form Works


Let's create a simple HTML form and try to understand how it works,
what are the different attributes available in the <form> tag and what
are they used for.

<html>

<body>

<form action="form-handler.php"
method="POST">

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


<br/>

Email: <input type="text" name="email">


<br/>

<input type="submit">

</form>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 5


WBP

</body>

</html>

In the code above, we have used the <form> tag to create an HTML
form, with input fields for Name and Email along with submit button
to submit the form-data.

In the <form> tag, we have two attributes, action and method, do you
know what they are for?

1. action: Using this attribute, we can specify the name of the file
which will collect and handle the form-data. In the example
above, we have provided name of a Php file.

2. method: This attribute specify the means of sending the form-data,


whether it will be submitted via POST method or GET method.

Below we have the same form with method as GET,

<html>

<body>

<form action="form-handler.php"
method="GET">

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


<br/>

Email: <input type="text" name="email">


<br/>

<input type="submit">

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 6


WBP

</form>

</body>

</html>

PHP Form Handling with POST


If we specify the form method to be POST, then the form-data is sent
to the server using the HTTP POST method.

Below, we have the code, to access the form-data in the Php file
specified in the action attribute of our HTML form.

<?php

// getting the value of name field

$name = $_POST["name"];

// getting the value of the email field

$email = $_POST["email"];

echo "Hi, ". $name . "<br>";

echo "Your email address: ". $email ."<br>";

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 7


WBP

?>

Hi, Studytonight

Your email address: [email protected]

You will get the above output, if you provide name as "Studytonight"
and email address as "[email protected]".

Form Controls

1. TextField-
The <input type="text"> defines a single-line input field for text input.

EX.

1.<html>
<body>

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

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

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

Password:<input type="password" name="password"><br><br>

<input type="submit">

</form>

</body>

</html>

2. <html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 8


WBP

Your email address is: <?php echo $_POST["email"]; ?><br>

Your password is: <?php echo $_POST["password"]; ?>

</body></html>

2. Text Area

The <textarea> element is often used in a form, to collect user inputs


like comments or reviews. A text area can hold an unlimited number of
characters, and the text renders in a fixed-width font (usually Courier).
The size of a text area is specified by the <cols> and <rows>
attributes (or with CSS).

Ex.

1.<html><body>
<form action="textareademo1.php" method="post">

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

Suggestion:

<textarea name="data" id="data" cols="20" rows="5">

</textarea><br><br>

<input type="submit" value="Submit">

</form>

</body></html>

2. <html><body>
<?php

if(isset($_POST["name"]))

echo "hello :".$_POST["name"]."<br>";

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 9


WBP

if(isset($_POST["data"]))

echo "suggestion :".$_POST["data"]; ?><br>

</body></html>

3. Radio Button

The <input type="radio"> defines a radio button.

Radio buttons are normally presented in radio groups (a collection of


radio buttons describing a set of related options). Only one radio
button in a group can be selected at the same time.

Note: The radio group must have share the same name (the value of
the name attribute) to be treated as a group. Once the radio group is
created, selecting any radio button in that group automatically
deselects any other selected radio button in the same group. You can
have as many radio groups on a page as you want, as long as each
group has its own name.

Note: The value attribute defines the unique value associated with
each radio button. The value is not shown to the user, but is the value
that is sent to the server on "submit" to identify which radio button
that was selected.

Ex.

1. <html>
<body>

<form action="radiobutton1.php" method="get">

<label>Select your gender:</label>

<br>

<input type="radio" name="gender" value="male" >Male<br>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 10


WBP

<input type="radio" name="gender" value="female"


>FeMale<br>

<input type="radio" name="gender" value="other" >Other<br>

<input type="submit" value="Submit">

</form>

</body>

</html>

2. <html><body>

<?php

if(isset($_GET["gender"]))

echo "Gender :".$_GET["gender"]; ?><br>

</body>

</html>

4. Check Box

The <input type="checkbox"> defines a checkbox.

The checkbox is shown as a square box that is ticked (checked) when


activated.

Checkboxes are used to let a user select one or more options of a


limited number of choices.

Ex

1. <html><body>
<form action="checkboxdemo1.php" method="post">

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 11


WBP

<label><ul style="list-style-type:circle;"><li><h1>Select
your hobbies:</h1></li></ul></label>

<br>

<input type="checkbox" name="sport[]" value="cricket"


>Cricket

<input type="checkbox" name="sport[]" value="football"


>Foot ball

<input type="checkbox" name="sport[]" value="basketball"


>Basket ball

<input type="checkbox" name="sport[]" value="chess" >Chess

<input type="submit" value="Submit">

</form></body></html>

2. <?php
$sport=$_POST["sport"];

if(empty($sport))

echo("You didn't select any hobies.");

else

$N = count($sport);

echo("You selected $N hobbies (s): ");

for($i=0; $i < $N; $i++)

echo($sport[$i] . " , ");

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 12


WBP

?>

5. List Box-

The list box is a graphical control element in the HTML document that
allows a user to select one or more options from the list of options.

Syntax

To create a list box, use the HTML element <select> which contains
two attributes Name and Size. The Name attribute is used to define
the name for calling the list box, and size attribute is used to specify
the numerical value that shows the how many options it contains.
<select Name="Name_of_list_box" Size="Number_of_options">

<option> List item 1 </option>

<option> List item 2 </option>

<option> List item 3 </option>

<option> List item N </option>

</select>

Ex. example uses the multiple attribute for selecting the multiple
options in a list. We can select multiple options from list box by
holding the ctrl key.

1.<html><body>
<form action="listdemo1.php" method="get">

<label>List Demo</label>

<br>Select class:

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 13


WBP

<select name="class" id="class" multiple="multiple"


size="2">

<option value="fyco">FYCO</option>

<option value="syco">SYCO</option>

<option value="tyco">TYCO</option>

</select>

<input type="submit" value="Submit">

</form></body></html>

2. <body>
<?php

if(isset($_GET["class"]))

echo "selected class is :".$_GET["class"]; ?><br>

</body></html>

6. Buttons-

The <input type="submit"> defines a button for submitting the form


data to a form-handler.

The form-handler is typically a file on the server with a script for


processing input data.

The form-handler is specified in the form's action attribute.

Ex
<html>

<head>This is button demo</head>

<body>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 14


WBP

<form method="get" action="buttondemo1.php">

<input type="submit" name="save" value="Save changes"


/><br><br>

<input type="submit" name="delete" value="delete" />

</form>

</body></html>

2. <?php
if($_SERVER['REQUEST_METHOD']=='GET')

if(isset($_GET['delete']))

echo "Delete bottun is clicked";

else

echo "Save changes button is clicked";

}}

?>

7. Hidden Controls

The <input type="hidden"> defines a hidden input field.

A hidden field let web developers include data that cannot be seen or
modified by users when a form is submitted.

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 15


WBP

A hidden field often stores what database record that needs to be


updated when the form is submitted.

Note: While the value is not displayed to the user in the page's
content, it is visible (and can be edited) using any browser's developer
tools or "View Source" functionality. Do not use hidden inputs as a
form of security!

Ex.

1. <html>
<head>this is hidden demo</head>

<body>

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

Class: <input type="hidden" name="class"


value="TYCO"><br><br>

Semester: <input type="hidden" name="sem"


value="sixth"><br><br>

<input type="submit">

</form></body></html>

2. <html>
<body>

class <?php echo $_POST["class"]; ?><br>

Your semester is: <?php echo $_POST["sem"]; ?><br>

</body></html>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 16


WBP

Working with Multiple forms

1. A web page having multiple forms-

A web page having multiple forms can be processed in two


types:

1. Posting each form to different PHP Script file for


processing

- Multiple functionality 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 file name 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 handling.

-Ex

1.<html>
<body>

<form name="mailform" action="multiform1.php"


method="post">

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 17


WBP

Email :<input type="text" name="email" id="email"


/><br><br>

<input type="submit" value="send email"


name="mailsubmit"><br><br>

</form>

<form name="mobileform" action="multiform2.php"


method="post">

Mobile :<input type="text" name="mobile" id="mobile"


/><br><br>

<input type="submit" value="Send mobile"


name="mobilesubmit">

</form></body></html>

2.<html>

<body>

<?php

if($_SERVER['REQUEST_METHOD']=='POST')

if(!empty($_POST['mailsubmit']))

echo "your mail is:".$_POST['email'];

?></body></html>

3. <?php

if($_SERVER['REQUEST_METHOD']=='POST')

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 18


WBP

if(!empty($_POST['mobilesubmit']))

echo "your mobile is:".$_POST['mobile'];

?>

2. Processing all form to single PHP script file for processing

-Multiple functionality 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 identifying 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 procession of all forms, which saves time in the creation and
handling of extra files.

Ex.

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 19


WBP

1. <html>
<body>

<form name="mailform" action="multiform3.php" method="post">

Email :<input type="text" name="email" id="email" /><br><br>

<input type="submit" value="send email"


name="mailsubmit"><br><br>

</form>

<form name="mobileform" action="multiform3.php" method="post">

Mobile :<input type="text" name="mobile" id="mobile" /><br><br>

<input type="submit" value="Send mobile" name="mobilesubmit">

</form>

</body></html>

2. <?php

if($_SERVER['REQUEST_METHOD']=='POST')

if(!empty($_POST['mobilesubmit']))

echo "your mobile is:".$_POST['mobile'];

else if(!empty($_POST['emailsubmit']))

echo "your email is:".$_POST['email'];

?>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 20


WBP

A form having multiple Submit Button-

Usually a HTML form has only one submit button but there are
situations when you might need to use more than one submit buttons
and have 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 the name of the button with the corresponding value of
the button using conditional statements.

The HTML part


First go to your HTML form and add as many submit buttons you want
inside the <form> tag, with one condition the name attribute of all the
submit buttons must be the same like the following

<input type="submit" name="btn_submit" value="Button 1" />


<input type="submit" name="btn_submit" value="Button 2" />
<input type="submit" name="btn_submit" value="Button 3" />
The text entered in the value attribute is shown in the output as the
submit button‟s caption. Next we‟ll move on to the PHP part.

The PHP part


As you might know when the submit button is pressed the browser
sends the values of the input elements within that <form> tag to the
file specified in the action attribute in the <form> tag. Along with that
the “value” of the submit button is also sent, so in the PHP part we‟ll
check which value is sent using elseif ladder and switch case
statements you can use the one you are comfortable with.

<?php
if($_REQUEST['btn_submit']=="Button 1")
{

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 21


WBP

print "You pressed Button 1";


}
else if($_REQUEST['btn_submit']=="Button 2")
{
print "You pressed Button 2";
}
else if($_REQUEST['btn_submit']=="Button 3")
{
print "You pressed Button 3";
}
?>
Doing the same using switch case

<?php
switch ($_REQUEST['btn_submit'])
{
case "Button 1":
print "You pressed Button 1";
break;
case "Button 2":
print "You pressed Button 2";
break;
case "Button 3":
print "You pressed Button 3";
break;
}
?>

Ex 2.1(HTML code)
<html><head>Multi-button form</head><br><br>
<body>

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


Enter first number: <input type="text" name="number1" id="no1">
<br><br>
Enter second number: <input type="text" name="number2" id="no2">
<br><br>
<input type="submit" name="add" value="Add">
<input type="submit" name="subtract" value="Subtract"> </form>

</body>
</html>
Ex 2.2(PHP Script)
<?php

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 22


WBP

if($_SERVER['REQUEST_METHOD']=='POST')
{
if (isset($_POST['add']))
{
echo ($_POST['number1']) + ($_POST['number2']);
}
else
{
echo ($_POST['number1']) - ($_POST['number2']);
}
}
?>
PHP Form Validation

Now we will learn some basic validations that can be easily applied to
the submitted form-data to validate it before performing any action
on it.
<?php
// getting the value of name field
$name = $_POST["name"];
// check if name is empty or not
if(empty($name)) {
echo "Name is required";
}
?>
In the code above we are checking whether the user has entered name
value in the form or not, similarly you can put a check on all the
mandatory form fields.

To validate email address, there is a special function available in PHP


which we can use to validate email addresses. The function is
filter_var($email, FILTER_VALIDATE_EMAIL), let's see how it works.
<?php

// getting the value of the email field

$email = $_POST["email"];

// checking if the email value is valid

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 23


WBP

if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo "Email value invalid";

?>

The filter_var() function returns true for a valid email address and
returns false for an invalid email address.

Validating a form in PHP depends on your requirements too. For


example, if you don't have any mandatory fields in your form, then
you don't have to worry about checking whether the submitted values
are empty or not.

If you have email address field, we suggest you validate it.

You can even add more validations like checking the input for
malicious codes like <script> tags using regular expressions.

Ex.2(HTML part)
<html>

<body>

<title>Validating form data</title>

<body>

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

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

Mobile no:<input type="text" name="mobileno"


id="mobileno"/><br><br>

email: <input type="text" name="email" id="email"/><br><br>

<input type="submit" name="submit" value="submit" /><br>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 24


WBP

</form>

</body>

</html>

(PHP SCRIPT)
<?php

if($_SERVER['REQUEST_METHOD']=='POST')

if(empty($_POST['name']))

echo "Name cant be blank<br>";

else

echo "<b>user name is</b>::".$_POST['name']."<br>";

if(!is_numeric($_POST['mobileno']))

echo "enter valid mobile no<br>";

else{

echo "<b>Mobile no is:</b>".$_POST['mobileno']."<br>";

/*$pattern='/\b[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}\b/';

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 25


WBP

if(!preg_match($pattern,$_POST['email']))

echo "enter valid email id.<br>";

else

echo "<b>your email is::</b> ".$_POST['email']."<br>";

}*/

$email1=$_POST['email'];

if(FILTER_VAR($email1,FILTER_VALIDATE_EMAIL))

echo "<b>your email is::</b> ".$email1."<br>";

else{

echo "enter valid email";

}?>

What is $_SERVER["PHP_SELF"]?

Sometimes we can avoid having an extra PHP file to handle/process


the form-data and can include the PHP code in the file with the HTML
form itself.

In such scenarios, we will have to submit the form to the same


webpage again, and we can use $_SERVER["PHP_SELF"] as the form
action

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 26


WBP

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>"


method="POST">

What this superglobal does is that it returns the filename of the


current webpage, which then acts as the action script.

But as this returns the existing filename from the URL, you must be a
little careful because users may inject some unwanted code from the
URL, so to avoid it, we can use the htmlspecialchars() function to
convert any special character in the string(URL in this case) into HTML
entities.

So you should use,

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);


?>" method="POST">

Superglobals
These are specially-defined array variables in PHP that make it easy for
you to get information about a request or its context. The
superglobals are available throughout your script. These variables can
be accessed from any function, class or any file without doing any
special task such as declaring any global variable etc. They are mainly
used to store and get information from one page to another etc in an
application.
Below is the list of superglobal variables available in PHP:
1. $GLOBALS
2. $_SERVER
3. $_REQUEST
4. $_GET

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 27


WBP

5. $_POST
6. $_SESSION
7. $_COOKIE
8. $_FILES
9. $_ENV
Let us now learn about some of these superglobals in details:

 $GLOBALS : It is a superglobal variable which is used to access


global variables from anywhere in the PHP script. PHP stores all the
global variables in array $GLOBALS[] where index holds the global
variable name, which can be accessed.
Below program illustrates the use of $GLOBALS in PHP:

<?php

$x = 300;

$y = 200;

Function multiplication(){

$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];

multiplication();

echo $z;

?>

Output :
60000

In the above code two global variables are declared $x and $y which
are assigned some value to them. Then a function multiplication() is
Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 28
WBP

defined to multiply the values of $x and $y and store in another


variable $z defined in the GLOBAL array.

$_SERVER : It is a PHP super global variable that stores the


information about headers, paths and script locations. Some of these
elements are used to get the information from the superglobal
variable $_SERVER.
Below program illustrates the use of $_SERVER in PHP:

<?php

echo $_SERVER['PHP_SELF'];

echo "<br>";

echo $_SERVER['SERVER_NAME'];

echo "<br>";

echo $_SERVER['HTTP_HOST'];

echo "<br>";

echo $_SERVER['HTTP_USER_AGENT'];

echo "<br>";

echo $_SERVER['SCRIPT_NAME'];

echo "<br>"

?>

 In the above code we used the $_SERVER elements to get some


information. We get the current file name which is worked on using
Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 29
WBP

„PHP_SELF‟ element. Then we get server name used currently using


„SERVER_NAME‟ element. And then we get the host name through
„HTTP_HOST‟.
 $_REQUEST : It is a superglobal variable which is used to collect the
data after submitting a HTML form. $_REQUEST is not used mostly,
because $_POST and $_GET perform the same task and are widely
used.
Below is the HTML and PHP code to explain how $_REQUEST works:
<!DOCTYPE html>
<html>
<body>

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


NAME: <input type="text" name="fname">
<button type="submit">SUBMIT</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']);
if(empty($name)){
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
In the above code we have created a form that takes the name as
input from the user and prints it‟s name on clicking of submit button.
We transport the data accepted in the form to the same page
using $_SERVER[„PHP_SELF‟] element as specified in the action
attribute, because we manipulate the data in the same page using the
PHP code. The data is retrieved using the $_REQUEST superglobal
array variable

$_POST : It is a super global variable used to collect data from the


HTML form after submitting it. When form uses method post to
transfer data, the data is not visible in the query string, because of
which security levels are maintained in this method.
Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 30
WBP

Below is the HTML and PHP code to explain how $_POST works:

<!DOCTYPE html>

<html><body>

<form method="post" action="<?php echo


$_SERVER['PHP_SELF'];?>">

<label for="name">Please enter your name: </label>

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

<label for="age">Please enter your age: </label>

<input name="age" type="text"><br>

<input type="submit" value="Submit">

<button type="submit">SUBMIT</button>

</form>

<?php

$nm=$_POST['name'];

$age=$_POST['age'];

echo "<strong>".$nm." is $age years old.</strong>";

?>

</body></html>

 In the above code we have created a form that takes name and age
of the user and accesses the data using $_POST super global

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 31


WBP

variable when they submit the data. Since each superglobal variable
is an array it can store more than one values. Hence we retrieved
name and age from the $_POST variable and stored them in $nm
and $age variables.
 $_GET : $_GET is a super global variable used to collect data from
the HTML form after submitting it. When form uses method get to
transfer data, the data is visible in the query string, therefore the
values are not hidden. $_GET super global array variable stores the
values that come in the URL.
 Below is the HTML and PHP code to explain how $_GET works:

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body bgcolor="cyan">

<?php

$name = $_GET['name'];

$city = $_GET['city'];

echo "<h1>This is ".$name." of ".$city."</h1><br>";

?>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 32


WBP

<img src = "2.jpg" alt = "nanilake" height = "400"


width="500" />

</body></html>

We are actually seeing half of the logic just now. In the above code
we have created a hyperlink image of Nainital Lake which will take
us to picture.php page and with it will also take the
paramerters name=”Nainilake” and city=”Nainital”.
That is when we click on the small image of Nainital Lake we will be
taken to the next page picture.php along with the parameters. As
the default method is get, these parameters will be passed to the
next page using get method and they will be visible in the address
bar. When we want to pass values to an address they are attached
to the address using a question mark (?).
Here the parameter name=Nainilake is attached to the address. If
we want to add more values, we can add them using ampersand
(&) after every key-value pair similarly as city=Nainital is added
using ampersand after the name parameter. Now after clicking on
the image of Nainital Lake we want the picture.php page to be
displayed with the value of parameter displayed along with it.

PHP Cookies

Cookie is a small piece of information stored as a file in the user's browser by


the web server. Once created, cookie is sent to the web server as header
information with every HTTP request.

You can use cookie to save any data but it should not exceed 1K(1024 bytes) in
size.

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 33


WBP

Real world Use of Cookies

To store user information like when he/she visited, what pages were visited on
the website etc, so that next time the user visits your website you can provide a
better user experience.

To store basic website specific information to know this is not the first visit of
user.

You can use cookies to store number of visits or view counter.

I hope this gives you an idea about how you can utilize cookies in your web
application.

Types of Cookies

There are two types of cookies, they are:

Session Cookie: This type of cookies are temporary and are expire as soon as
the session ends or the browser is closed.

Persistent Cookie: To make a cookie persistent we must provide it with an


expiration time. Then the cookie will only expire after the given expiration time,
until then it will be a valid cookie.

Creating a Cookie in PHP

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

Below we have the syntax for the function,

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

The first argument which defines the name of the cookie is mandatory, rest all
are optional arguments. Let's understand what are the available arguments that
we can supply to the setcookie() function to set a cookie.

Argument What is it for?

nameUsed to specify the name of the cookie. It is a mandatory argument.


Name of the cookie must be a string.

value Used to store any value in the cookie. It is generally saved as a pair with
name. For example, name is userid and value is 7007, the userid for any user.

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 34


WBP

expire Used to set the expiration time for a cookie. if you do not provide
any value, the cookie will be treated as a session cookie and will expire when
the browser is closed.

path Used to set a web URL in the cookie. If set, the cookie will be accessible
only from that URL. To make a cookie accessible through a domain, set '/' as
cookie path.

domain The domain of your web application. It can be used to limit access
of cookie for sub-domains. For example, if you set the domain value as
wwww.studytonight.com, then the cookie will be inaccessible from
blog.studytonight.com

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

So if we want to create a cookie to store the name of the user who visited your
website, and set an expiration time of a week, then we can do it like this,

<?php

setcookie("username", "I am abhishek", time()+60*60*24*7);

?>

To access a stored cookie we use the $_COOKIE global variable, and can use
the isset() methos to check whether the cookie is set or not.

Let's have a complete example where we will set a cookie and then retrieve it to
show its value in the HTML page.

<?php

// set the cookie

setcookie("username", "I am abhishek", time()+60*60*24*7);

?>

<html>

<body>

<?php

// check if the cookie exists

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 35


WBP

if(isset($_COOKIE["username"]))

echo "Cookie set with value: ".$_COOKIE["username"];

else

echo "cookie not set!";

?>

</body>

</html>

So by providing the name of the cookie inside the square brakets with the
global variable $_COOKIE[] we can access the cookie.

NOTE: setcookie() function should be placed before the starting HTML


tag(<html>).

Updating Cookie in PHP

To update/modify a cookie, simply set it again. For example, if we want to


update the username stored in the cookie created above, we can do it using
setcookie() method again,

<?php

// updating the cookie

setcookie("username", "I am NOTabhishek", time()+60*60*24*7);

?>

<html>

<body>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 36


WBP

<?php

// check if the cookie exists

if(isset($_COOKIE["username"]))

echo "Cookie set with value: ".$_COOKIE["username"];

else

echo "cookie not set!";

?>

</body>

</html>

We just update the value of username cookie from iamabhishek to


iamNOTabhishek.

Delete a Cookie in PHP

To delete/remove a cookie, we need to expire the cookie, which can be done by


updating the cookie using the setcookie() function with expiration date in past.

<?php

// updating the cookie

setcookie("username", "I am NOT abhishek", time() - 3600);

?>

<html>

<body>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 37


WBP

<?php

echo "cookie username is deleted!";

?>

</body>

</html>

And with this, we now know how to create a cookie, how to update it and how
to delete it when we no longer need it

PHP Sessions for State Management

To store information accessible across web pages, we use sessions. Session is


not stored on the user browser like Cookies, hence it is a more secure option.

As we know HTTP is a stateless protocol, if a user visits a webpage and perform


some action, there is no way to remember what he did when the user navigates
to the next webpage.

Let's take a practical example, when you log into your facebook account, by
providing your email address and password, until and unless you logout, the
web application remembers who you are and display what your friends are
posting and liking on your News Feed, you can update your profile, send
someone message, join a group etc, this is accomplished by Session.

When a user logs into their account on any web application, a session is created
for them, and in the session their username or userid or some other unique
identifier is stored, which is then used on the consecutive webpages to show
information specific to that user. On logout, the session is destroyed.

Session is not limited by any size limit, you can store any information in the
session, irrespective of its size.

Before we move on to how to start, update and end a session in PHP, let's learn
a few real world use of session.

Real world Use of Session

Web applications which require a user to login, use session to store user
information, so that on every webpage related information can be displayed to
the user.

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 38


WBP

In e-Commerce websotes, shopping cart is generally saved as part of session.

Start a Session in PHP

In PHP we can start a session by using the session_start() function. And data is
stored in the session using session variable, which can be assigned different
values using global variable $_SESSION

In simpler words, using the function session_start() we initialize the session, in


which we can store information using the session variable $_SESSION.

Let's take an example, below we have a webpage with Php file named
first_page.php

<?php

// start the session

session_start();

// set the session variable

$_SESSION["username"] = "iamabhishek";

$_SESSION["userid"] = "1";

?>

<html>

<body>

<?php

echo "Session variable is set.";

?>

<a href="second_page.php">Go to Second Page</a>

</body>

</html>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 39


WBP

NOTE: The function session_start() should be the first statement of the page,
before any HTML tag.

Getting PHP Session Variable Values

In the code above, we have started a session and set two session variables.
Above webpage will also have a link to navigate to Second page
second_page.php.

Below is the code for second_page.php, in which we fetch values from the
session variable which are set in the first_page.php.

<?php

// start the session

session_start();

// get the session variable values

$username = $_SESSION["username"];

$userid = $_SESSION["userid"];

?>

<html>

<body>

<?php

echo "Username is: ".$username."<br/>";

echo "User id is: ".$userid;

?>

</body>

</html>

Username is: I am abhishek

User id is: 1

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 40


WBP

You must be thinking, why we used session_start() here although we did not set
any new values in the session variable.

session_start() function is used to initialize a new session and to fetch the


ongoing session(if already started), and then, using the $_SESSION global
variable, we can either set new values into the session or get the saved values.

If there are too many values stored in the session, and you don't know which
one do you want to get, you can use the below code to print all the current
session variable data.

<?php

// start the session

session_start();

?>

<html>

<body>

<?php

print_r($_SESSION);

?>

</body>

</html>

Array (

[username] => iam abhishek,

[userid] => 1

Update Session Variable in PHP

To update any value stored in the session variable, start the session by calling
session_start() function and then simply overwrite the vakue to update session
variable.

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 41


WBP

<?php

// start the session

session_start();

// update the session variable values

$_SESSION["userid"] = "1111";

?>

<html>

<body>

<?php

echo "Username is: ".$username."<br/>";

echo "User id is: ".$userid;

?>

</body>

</html>

Username is: iamabhishek

User id is: 1111

We just updated the value of userid in the session variable from 1 to 1111.

Destroy a Session in PHP

To clean the session variable or to remove all the stored values from the session
variable we can use the function session_unset() and to detroy the session, we
use session_destroy() function.

<?php

// start the session

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 42


WBP

session_start();

?>

<html>

<body>

<?php

// clean the session variable

session_unset();

// destroy the session

session_destroy();

?>

</body>

</html>

We use these functions on pages like logout or checkout in case of an e-


Commerce website to clean the session variable off the user specific data and to
eventually destroy the current session.

Sending Email
PHP mail is the built in PHP function that is used to send emails from PHP
scripts.

The mail function accepts the following parameters;

 Email address
 Subject
 Message
 CC or BC email addresses
o It’s a cost effective way of notifying users on important events.
o Let users contact you via email by providing a contact us form
on the website that emails the provided content.
o Developers can use it to receive system errors by email
o You can use it to email your newsletter subscribers.

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 43


WBP

o You can use it to send password reset links to users who forget
their passwords
o You can use it to email activation/confirmation links. This is
useful when registering users and verifying their email addresses

Why/When to use the mail PHP


Sending mail using PHP
The PHP mail function has the following basic syntax

<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>

HERE,

 “$to_email_address” is the email address of the mail recipient


 “$subject” is the email subject
 “$message” is the message to be sent.
 “[$headers]” is optional, it can be used to include information such as
CC, BCC
o CC is the acronym for carbon copy. It’s used when you want to
send a copy to an interested person i.e. a complaint email sent
to a company can also be sent as CC to the complaints board.
o BCC is the acronym for blind carbon copy. It is similar to CC. The
email addresses included in the BCC section will not be shown to
the other recipients.

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

Parameter Values
Parameter Description

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 44


WBP

to Required. Specifies the receiver / receivers of the email

subject Required. Specifies the subject of the email. Note: 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.

Windows note: If a full stop is found on the beginning of a line in the


message, it might be removed. To solve this problem, replace the full
stop with a double dot:
<?php
$txt = str_replace("\n.", "\n..", $txt);
?>

headers Optional. Specifies additional headers, like From, Cc, and Bcc. The
additional headers should be separated with a CRLF (\r\n).

Note: When sending an email, it must contain a From header. This can
be set with this parameter or in the php.ini file.

parameters Optional. Specifies an additional parameter to the sendmail program


(the one defined in the sendmail_path configuration setting). (i.e. this
can be used to set the envelope sender address when using sendmail
with the -f sendmail option)

Example
Send a simple email:

<?php
// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 45


WBP

$msg = wordwrap($msg,70);

// send email
mail("[email protected]","My subject",$msg);
?>

Simple Mail Transmission Protocol (SMTP)


PHP mailer uses Simple Mail Transmission Protocol (SMTP) to send mail.

On a hosted server, the SMTP settings would have already been set.

The SMTP mail settings can be configured from “php.ini” file in the PHP
installation folder.

Configuring SMTP settings on your localhost Assuming you are using xampp
on windows, locate the “php.ini” in the directory “C:\xampp\php”.

 Open it using notepad or any text editor. We will use notepad in this
example. Click on the edit menu

 Click on Find… menu

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 46


WBP

 The find dialog menu will appear

 Click on Find Next button

 Locate the entries


o [mail function]
o ; XAMPP: Don’t remove the semi column if you want to work
with an SMTP Server like Mercury
o ; SMTP = localhost

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 47


WBP

o ; smtp_port = 25
o Remove the semi colons before SMTP and smtp_port and set the
SMTP to your smtp server and the port to your smtp port. Your
settings should look as follows
 SMTP = smtp.example.com
 smtp_port = 25
 Note the SMTP settings can be gotten from your web
hosting providers.
 If the server requires authentication, then add the
following lines.
 auth_username = [email protected]
 auth_password = example_password
 Save the new changes.
 Restart Apache server.

Php Mail Example

Let’s now look at an example that sends a simple mail.

<?php
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>

Output:

Note: the above example only takes the 4 mandatory parameters.

You should replace the above fictitious email address with a real email
address.

Ex2

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 48


WBP

<?php

// the message

$msg = "this is test mail";

$to="[email protected]";

$sub="test mail";

// use wordwrap() if lines are longer than 70 characters

$msg = wordwrap($msg,70);

$from="[email protected]";

// send email

if(mail($to,$sub,$msg,$from))

echo "mail send successfully";

else

echo "mail failed";

?>

Created by Mrs.R.S.Patil,SGM Poly,Mahagaon Page 49

You might also like