Chapter04 Full Discription
Chapter04 Full Discription
4.1 Creating a webpage using GUI components, Browser Role-GET and POST
methods, Server Role,
4.2 Form controls: text box, text area, radio button, check box, list, button
4.3 Working with multiple forms:
- A web page having many forms
- A form having multiple submit buttons.
4.4 Web page validation
4.5 Cookies - use of cookies, Attributes of cookies, create cookies, modify cookies
value and delete cookies
4.6 Session - Use of session, start session, get session variables, destroy session.
4.7 Sending Email
Introduction to Webpage
● To run any code on server or to get connected with PHP on server we need to
set up Web pages in a specific fashion.
● Two methods “get” and “post” mentioned in form are commonly used to
send data from HTML controls to PHP script on server.
● URL is used to specify location, which helps browser understand where to
send the data on server mentioned in the “action: attribute of a form”.
● Two methods get and post mentioned in form are commonly used to send
data from HTML controls to PHP script on server.
● URL is used to specify the location which specifies where to send data on
server.
● PHP script handles both displaying of HTML controls and then reading of
data from HTML controls when the user clicks on the submit button.
Creating a Webpage using GUI components
A document that containing blank fields, that the user can fill the data or user can
select the data is known as form.
To get form data, we need to use PHP superglobals. $_GET and $_POST.
The form request may be get or post. To retrieve data from get request we need to
use $_GET, for post request $_POST
Browser Role - GET and POST Methods
● Browser used one of the two HTTP methods - GET and POST to communicate
with the server. Both methods are used to pass the information differently to
the server.
GET method:
● The GET method sends the encoded user information appended to the page
request (to the url). The code and the encoded information are separated by the ?
character.
● http://www.test.com/index.htm?name1=value1&name2=value2
● The GET method produces a long string that appears in our server logs, in the
browser’s location:box.
Never use GET method if we have password or other sensitive information to be
sent to the server. Get cannot be used to send binary data, like images or word
documents, to the server.
PHP provides $_GET associative array to access all the sent information using
GET method.
POST Method
The POST method transfers information via HTTP headers. The information is
encoded as described in case of GET method and put into a header called
QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on
HTTP protocol. By using Secure HTTP you can make sure that your information
is secure.
The PHP provides $_POST associative array to access all the sent information
using POST method.
Difference between get and post
1. Information sent from a form with the 1. Information sent from a form with the
get method is visible to everyone(all post method is invisible to others(all
variable names and values are names/values are embedded within the
displayed in the URL) body of the HTTP request)
2. GET has limits on the amount of 2. Post has no limits on the amount of
information to send. The limitation is information to send.
about 2048 characters 3. $_POST is an array of variables passed
3. $_GET is an array of variables passed to the current script via the HTTP POST
to the current script via the URL method.
parameters. 4. Cannot be bookmarked.
4. Can be bookmarked. 5. Not cached.
5. Can be cached. 6. Parameters are not saved in browser
6. Parameters remain in browser history. history.
Server Role
PHP is a server side scripting language. That means its processing happens in the
server by consuming server's resources and sends only the output to the client.
Textbox
A text input field allows the user to enter a single line of text
Textbox field enable the user to input text information to be used by the program
Input.html
</form>
Step 2:Now the hello.php program can be as follows-
<?php
$name=$_GET["user"];
echo"Hello,$name";
?>
step3:
Step 4
Text Area
A text area field is similar to a text input field but it allows the user to enter multiple
line of text
Syntax
}
if(!empty($_POST['submit_feedback
']))
{
echo "<h3>we value your
feedback:</h3>";
- A form having multiple submit buttons.
<form method="post"> <input type="submit" name="mul"
<h3>Simple Arithmetic Calculator</h3> value="MULTIPLICATION"/>
Number 1: <input type="text" size="5" <input type="submit" name="div"
name="num1"/> value="DIVISION"/>
<br/><br> <?PHP
Number 2: <input type="text" size="5" if(!empty($_POST['add'])) {
name="num2"/> $result=$_POST['num1']+$_PO
<br/><br> ST['num2'];
<input type="submit" name="add" echo "<h3> Addition:
value="ADDITION"/> ".$result."</h3>";
<input type="submit" name="sub" }
value="SUBTRACTION"/>
- A form having multiple submit buttons.
if(!empty($_POST['sub'])) echo "<h3> Multiplication:
{ ".$result."</h3>";
$result=$_POST['num1']- }
$_POST['num2']; if(!empty($_POST['div']))
echo "<h3> Subtraction: {
".$result."</h3>"; $result=$_POST['num1']/$_POS
} T['num2'];
if(!empty($_POST['mul'])) echo "<h3> Division:
{ ".$result."</h3>";
$result=$_POST['num1']*$_POST['num2 }
']; ?>
Validation
1.Required field will check whether the field is filled or not in the proper way.
Most of cases we will use the * symbol for required field.
3. There are two types of validation available in PHP. They are as follows −
Server Side Validation − After submitted by data, The data is sent to a server and
performs validation checks in the server machine.
Validation
$website = input($_POST["site"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-
z0-9+&@#\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
Above syntax will verify whether a given URL is valid or not. It should allow
some keywords as https, ftp, www, a-z, 0-9,..etc..
2.Valid Email
$email = input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid format and please re-enter valid email";
}
Above syntax will verify whether a given Email address is well-formed or not.if it
is not, it will show an error message.
Predefined function for validation in php
1.The filterName() function validates input value as a person's name. A valid name
can only contain alphabetical characters (a-z, A-Z).
3.The filterString() function only sanitizes the input value by stripping HTML tags
and special characters. It doesn't validate the input value against anything.
What is cookie?
PHP cookie is a small piece of information which is stored at client browser. It is used
to recognize the user.
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.In short, cookie can be created, sent and received at server
end.
Here,
3) Other page requests from the user will return the cookie name and value
What is cookie?
PHP cookie is a small piece of information which is stored at client browser. It is used
to recognize the user.
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.In short, cookie can be created, sent and received at server
end.
Types of Cookies
There are 2 types of cookies:
(1) Session Based which expire at the end of the session.
(2) Persistent cookies which are written on hard disk.
Session cookies expire at the end of the session.
● This means, when you close your browser window, the session cookie is deleted.
● A session cookie may be created when you visit a site or portion of a site.
● The cookie exists for the duration of your visit. This website only uses session
cookies.
● Session cookies are temporary means they are stored temporarily in memory and
are automatically removed when the browser closes or the session ends.
● For example, a session cookie is created when you use the Personal Login to
access secured pages.
Persistent Cookies
● Persistent cookies do not expire at the end of the session.
● Persistent cookies are also called as permanent cookies or stored cookies.
● A cookies that is stored on the hard disk until it expires or until we delete the
cookie.
● Persistent cookies are used to collect identifying information about the user,
such as Web surfing behavior or user preferences for a specific Web site.
Use of Cookies
● A cookie is often used to identify a user.
● A cookie is a small file that the server embeds on the user’s computer.
● Each time the same computer requests a page with a browser, it will send the
cookie too.
Name - Used 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.
Expiry - 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 browser will return the cookie only for URLs within this domain. The
default is the server hostname.
Secure: This can be set to 1 to specify that the cookie should only be sent by
secure transmission using HTTPs otherwise set to 0 which mean cookie can be
sent by regular HTTP.
PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag.
For each cookie this function has to be called separately.The first argument which
defines the name of the cookie is mandatory, rest all are optional arguments.
setcookie(name, value, expire, path, domain, security);
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
Example
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0); // cookie will expire in
1 hour
setcookie("age", "36", time()+(86400 * 30), "/", "", 0);//expire after 30 days
?>
The above example creates a cookie named "user" with the value "John Doe". The
cookie will expire after 30 days (86400 * 30). The "/" means that the cookie is
available in entire website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:
Note: The setcookie() function must appear BEFORE the <html> tag.
<?php
// set the cookie
setcookie("username", "Dashrath", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
Modify cookies value
To modify a cookie, just set (again) the cookie using the setcookie() function:
<?php
// updating the cookie
setcookie("superstar", "Akashy Kumar", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["superstar"]))
{
echo "Cookie set with value: ".$_COOKIE["superstar"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
Delete cookies
<?php
// set the expiration date to one hour ago
setcookie("user", "Rajani Kant", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Session - Use of session, start session, get session variables, destroy session.
PHP session is used to store and pass information from one page to another
temporarily (until user close the website).
PHP session technique is widely used in shopping websites where we need to store
and pass cart information e.g. username, product code, product name, product price
etc from one page to another.
PHP session creates unique user id for each browser to recognize the user and avoid
conflict between multiple browsers.
Use of Session
● A PHP session is used to store data on a server rather than the computer of the
user.
● The SID is used to link the user with his information on the server like posts,
emails etc.
PHP session_start() function
PHP session_start() function is used to start the session. It starts a new or resumes
existing session. It returns existing session if session is created already. If session
is not available, it creates and returns new session.
Syntax
Example
session_start();
<?php A session is started with the
// Start the session session_start() function.
session_start(); Session variables are set with the PHP
?> global variable:
<!DOCTYPE html> $_SESSION.
<html> Now, let's create a new page called
<body> "demo_session1.php".
<?php In this page, we start a new PHP session
// Set session variables and set some session variables:
$_SESSION["favcolor"] = "green"; Note: The session_start() function must
$_SESSION["favanimal"] = "cat"; be the very first thing in your document.
echo "Session variables are set."; Before any HTML tags.
?>
</body></html>
Modify a PHP Session Variable // to change a session variable, just
To change a session variable, just overwrite it
overwrite it: $_SESSION["favcolor"] = "yellow";
Example print_r($_SESSION);
<?php ?>
session_start(); </body>
?> </html>
<!DOCTYPE html>
<html> To change a session variable, just
<body> overwrite it:
<?php
Destroy a PHP Session
To remove all global session
<?php variables and destroy the session, use
session_start(); session_unset() and
?> session_destroy():
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?></body> </html>
PHP mail:
it 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 BCC email addresses
It’s a cost effective way of notifying users on important events.
Let users contact you via email by providing a contact us form on the website that
emails the provided content.
Developers can use it to receive system errors by email
You can use it to email your newsletter subscribers.
You can use it to send password reset links to users who forget their passwords
You can use it to email activation/confirmation links. This is useful when
registering users and verifying their email addresses.
Sending mail using PHP
The PHP mail function has the following basic syntax
<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>
1. “$to_email_address” is the email address of the mail recipient
2. “$subject” is the email subject
3. “$message” is the message to be sent.
4. “[$headers]” is optional, it can be used to include information such as CC,
BCC
● 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.
● 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.
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.
● Configure SMTP settings on your localhost Assuming you are using xampp on
windows, locate the “php.ini” in the directory “C:\xampp\php”.
File :-Php.ini
//email function
smtp_port=465
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
mail.add_x_header=on
File:- sendemail.ini
smtp_server=smtp.gmail.com
smtp_port=465
smtp_ssl=auto
error_logfile=error.log
[email protected]
auth_password=
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);
?>