WBP Topic 4 Notes
WBP Topic 4 Notes
Topic 4
<html>
<body>
</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>
</body>
</html>
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>
</body>
</html>
<html>
<body>
</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.
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
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.
Note: GET should NEVER be used for sending passwords or other sensitive
information!
However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.
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>
<?php
if(isset($_POST["submit"]))
echo $_POST['name']."<br>";
echo $_POST['email'];
?>
</body>
</html>
PHP provides two superglobals $_GET and $_POST for collecting form-
data for processing.
<html>
<body>
<form action="form-handler.php"
method="POST">
<input type="submit">
</form>
</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.
<html>
<body>
<form action="form-handler.php"
method="GET">
<input type="submit">
</form>
</body>
</html>
Below, we have the code, to access the form-data in the Php file
specified in the action attribute of our HTML form.
<?php
$name = $_POST["name"];
$email = $_POST["email"];
?>
Hi, Studytonight
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>
<input type="submit">
</form>
</body>
</html>
2. <html>
<body>
</body></html>
2. Text Area
Ex.
1.<html><body>
<form action="textareademo1.php" method="post">
Suggestion:
</textarea><br><br>
</form>
</body></html>
2. <html><body>
<?php
if(isset($_POST["name"]))
if(isset($_POST["data"]))
</body></html>
3. Radio Button
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>
<br>
</form>
</body>
</html>
2. <html><body>
<?php
if(isset($_GET["gender"]))
</body>
</html>
4. Check Box
Ex
1. <html><body>
<form action="checkboxdemo1.php" method="post">
<label><ul style="list-style-type:circle;"><li><h1>Select
your hobbies:</h1></li></ul></label>
<br>
</form></body></html>
2. <?php
$sport=$_POST["sport"];
if(empty($sport))
else
$N = count($sport);
?>
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">
</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:
<option value="fyco">FYCO</option>
<option value="syco">SYCO</option>
<option value="tyco">TYCO</option>
</select>
</form></body></html>
2. <body>
<?php
if(isset($_GET["class"]))
</body></html>
6. Buttons-
Ex
<html>
<body>
</form>
</body></html>
2. <?php
if($_SERVER['REQUEST_METHOD']=='GET')
if(isset($_GET['delete']))
else
}}
?>
7. Hidden Controls
A hidden field let web developers include data that cannot be seen or
modified by users when a 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>
<input type="submit">
</form></body></html>
2. <html>
<body>
</body></html>
-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.
-Ex
1.<html>
<body>
</form>
</form></body></html>
2.<html>
<body>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
if(!empty($_POST['mailsubmit']))
?></body></html>
3. <?php
if($_SERVER['REQUEST_METHOD']=='POST')
if(!empty($_POST['mobilesubmit']))
?>
-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
Ex.
1. <html>
<body>
</form>
</form>
</body></html>
2. <?php
if($_SERVER['REQUEST_METHOD']=='POST')
if(!empty($_POST['mobilesubmit']))
else if(!empty($_POST['emailsubmit']))
?>
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.
<?php
if($_REQUEST['btn_submit']=="Button 1")
{
<?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>
</body>
</html>
Ex 2.2(PHP Script)
<?php
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.
$email = $_POST["email"];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
?>
The filter_var() function returns true for a valid email address and
returns false for an invalid email address.
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>
<body>
</form>
</body>
</html>
(PHP SCRIPT)
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
if(empty($_POST['name']))
else
if(!is_numeric($_POST['mobileno']))
else{
/*$pattern='/\b[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}\b/';
if(!preg_match($pattern,$_POST['email']))
else
}*/
$email1=$_POST['email'];
if(FILTER_VAR($email1,FILTER_VALIDATE_EMAIL))
else{
}?>
What is $_SERVER["PHP_SELF"]?
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.
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
5. $_POST
6. $_SESSION
7. $_COOKIE
8. $_FILES
9. $_ENV
Let us now learn about some of these superglobals in details:
<?php
$x = 300;
$y = 200;
Function multiplication(){
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
<?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>"
?>
Below is the HTML and PHP code to explain how $_POST works:
<!DOCTYPE html>
<html><body>
<button type="submit">SUBMIT</button>
</form>
<?php
$nm=$_POST['name'];
$age=$_POST['age'];
?>
</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
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'];
?>
</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
You can use cookie to save any data but it should not exceed 1K(1024 bytes) in
size.
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.
I hope this gives you an idea about how you can utilize cookies in your web
application.
Types of Cookies
Session Cookie: This type of cookies are temporary and are expire as soon as
the session ends or the browser is closed.
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.
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.
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
?>
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
?>
<html>
<body>
<?php
if(isset($_COOKIE["username"]))
else
?>
</body>
</html>
So by providing the name of the cookie inside the square brakets with the
global variable $_COOKIE[] we can access the cookie.
<?php
?>
<html>
<body>
<?php
if(isset($_COOKIE["username"]))
else
?>
</body>
</html>
<?php
?>
<html>
<body>
<?php
?>
</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
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.
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.
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
Let's take an example, below we have a webpage with Php file named
first_page.php
<?php
session_start();
$_SESSION["username"] = "iamabhishek";
$_SESSION["userid"] = "1";
?>
<html>
<body>
<?php
?>
</body>
</html>
NOTE: The function session_start() should be the first statement of the page,
before any HTML tag.
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
session_start();
$username = $_SESSION["username"];
$userid = $_SESSION["userid"];
?>
<html>
<body>
<?php
?>
</body>
</html>
User id is: 1
You must be thinking, why we used session_start() here although we did not set
any new values in the session variable.
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
session_start();
?>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Array (
[userid] => 1
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.
<?php
session_start();
$_SESSION["userid"] = "1111";
?>
<html>
<body>
<?php
?>
</body>
</html>
We just updated the value of userid in the session variable from 1 to 1111.
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
session_start();
?>
<html>
<body>
<?php
session_unset();
session_destroy();
?>
</body>
</html>
Sending Email
PHP mail is the built in PHP function that is used to send emails from PHP
scripts.
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.
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
<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>
HERE,
Syntax
mail(to,subject,message,headers,parameters);
Parameter Values
Parameter Description
subject Required. Specifies the subject of the email. Note: This parameter
cannot contain any newline characters
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.
Example
Send a simple email:
<?php
// the message
$msg = "First line of text\nSecond line of text";
$msg = wordwrap($msg,70);
// send email
mail("[email protected]","My subject",$msg);
?>
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
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
$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:
You should replace the above fictitious email address with a real email
address.
Ex2
<?php
// the message
$to="[email protected]";
$sub="test mail";
$msg = wordwrap($msg,70);
$from="[email protected]";
// send email
if(mail($to,$sub,$msg,$from))
else
?>