PHP_Ch_4
PHP_Ch_4
HTML controls like text fields, check boxes, radio buttons etc. enclosed in HTML
form are used to collect data from user.
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 helps browser understand where to
send the data on server mentioned in the "action" attribute of a form.
For example, a simple form with a text field and submit button, text field is used to
get name from users and we have to make the browser know where to send the
name data when the user clicks on Submit button.
<html>
<head>
<title> Sample PHP Program </title>
</head>
<body>
<form method="get" action=php_readdata.php>
<input name="username" type="text">
<input type="submit" value="Submit">
</form
</body>
</html>
Browser Role - GET and POST Methods -
Browser used one of the two HTTP (Hypertext Transfer Protocol) methods GET and
POST to communicate with the server. Both methods GET and POST are used to pass
the information differently to the server.
GET Method
This is the built in PHP super global array variable that is used to get values
submitted via HTTP GET method.
Data in GET method is sent as URL parameters that are usually strings of name and
value pairs separated by ampersands (&).
http://www.abc.com/dataread.php?name=ram&age=20.
The name and age in the URL are the GET parameters; ram and 20 are the value of
those parameters.
More than one parameter-value can be embedded in the URL by concatenating with
ampersands (&).
Only simple text data can only be sent through GET method.
Sensitive information such as the username and password can't be sent as it will be
visible in the query string and it can store in browser memory as visited page.
Syntax :
<?php
$_GET['variable_name'];
?>
<html>
<body>
<form action="student.php" method="get">
Name: <input type="text" name="name">
Address: <input type="text" name="address">
<input type="submit">
</form>
</body>
</html>
Student.php
<html>
<body>
Welcome: <?php echo $_GET["name"]; ?>!
Your address is: <?php echo $_GET["address"]; ?>
</body>
</html>
Advantages of using the GET Method -
• Since the data sent by the GET method are displayed in the URL.
• GET requests can be cached and GET requests remain in the browser history.
• The GET method is not suitable for passing sensitive information such as the
username and password, because these are fully visible in the URL string as well
as stored in the client browser's memory as a visited page.
• Because the GET method assigns data to a server environment variable, the
length of the URL is limited. So, there is a limitation for the total data to be sent.
POST Method -
• This is the built in PHP super global array variable that is used to get values
submitted via HTTP POST method.
• User entered Information is never visible in the URL query string as it is visible
in GET. The POST method can be used to send the much larger amount of data
and text data as well as binary data (uploading a file).
• Data sent by the POST method is not visible in the URL, so it is not possible to
bookmark the page with specific query.
• Super global variable $_POST is used to access all the information sent through
an HTML form using the post method.
• A good example of using post method is when submitting login details to the
server.
Syntax:
<?php
$_POST['variable_name'];
?>
Where "$_POST[“ “] is the PHP array and
"variable_name" is the URL variable name.
Example: Student.html
<html>
<body>
<form action="student.php" method="post">
Name: <input type="text" name="name“ id="name">
Address: <input "text" name=“address“ id="address">
It is more secure than GET because user-entered information is never visible in the
URL query string or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can
send text data as well as binary data (uploading a file) using POST.
Since the data sent by the POST method is not visible in the URL, so it is not possible
to bookmark the page with specific query.
• Server processes the request and returns a result, in the form of a response to
the client.
• The response from the server contains status information about the request and
requested content.
1. Client Request
2. Server Parse Request and Send Response
3. Client interpret Responded Text/HTML etc...
Example : a.html
<html>
<head>
<title> PHP Server </title>
</head>
<body>
<form method="post" action="sample.php">
<label>Mail id:</label>
<input type="text" name="mailid" id=" mailid">
<input type="submit" value="Submit">
</form>
</body>
</html>
sample.php
<?php
if(isset($_POST["mailid"])){
echo "<p>Mail id: ".$_POST["mailid"] . "</p>";
}
?>
POST method is used data will be invisible to everyone and embedded within the
body of the HTTP request.
On the server side a super global variable $_POST is used by PHP to create an
associative array with an access key ($_POST['name as key']).
Data is assessed using key and based on collected data processing takes place
and the result is provided as a response to the client.
Embedding PHP in HTML
We can add rest of the lines to the output by just keeping them outside of PHP
blocks instead of outputting each of those lines using PHP. This saves PHP
processing resources and lets us have clean and readable files in our development.
Example: Info.php
<html>
<body>
<h1> Using PHP and HTML together </h1>
Here is your PHP information:
<br>
<?php
phpinfo();
?>
</body>
</html>
Form Control –
Text Field -
Text Field is used to take a single line input from the user.
Text Field will be included in <form> element of a web page that will be used to
take user input, which will be sent to PHP script available on the server.
Data on the server will be fetched by any one of the super global variable $_GET
and $_POST, after receiving it will be processed and the result will be sent to the
user in a form of response.
Example 1: textfielddemo.html
<html>
<head>
<title> Text Field Demo</title>
</head>
<body>
<label>Mobile Number:</label>
</form>
</body>
</html>
Example 2: textdemo.php
<?php
if(isset($_GET["mobileno"])){
?>
Text Area -
Text Area is used to take multi line input from the user. Text Area will be included
in <form> element of a web page that will be used to take multi line input like
suggestions,
address, feedback from users, which will be sent to PHP script available on the
server. Data on the server will be fetched by any one of the superglobal variable
$_GET and $_POST, after receiving it will be
Example 1: textareademo.html
<html>
<head>
<title>Text Area Demo</title> </head>
<body>
</form>
</body>
</html>
Example 2: phptextareademo.php
<?php
if(isset($_GET["data"])){
}
?>
Radio Button -
• Radio Button is used to make the user select single choice from a number of
available choices.
• Radio Button will be included in <form> element of a web page that will be used
single choice input from the user, which will be sent to PHP script available on
the server.
• Data on the server will be fetched by any of the super global variable $_GET and
$_POST, after receiving it will be processed and the result will be sent to the user
in a form of response.
Check Box -
Check Box is used to select one or more options from available options displayed for
selection.
Check Box will be displayed as square box which will be activated when ticked
(checked).
List Box
List Box is used to create drop down list of options.
HTML <select> tag will be include in <form>element of a web page that will be used
to display dropdown list where user can select single or multiple options (when
multiple attribute is set), which will be send to PHP script available on server.
The <option> tag will be used in <select> tag in order to drop list of options.
Buttons
Button is created using <button> tag.
Text and Image can be displayed on the button by placing the text or image
between the opening and button.
Buttons has to be added with actions using JavaScript or by associating the button
with a form.
In we are creating button in form <input> tag is used to create a button. For
Example, a Web page buttondemo.html has a two buttons "Save Changes" and
"Delete", by clicking any of the
Working 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.
Disadvantage is that we have to write separate PHP script for each form.
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.
A Form having Multiple Submit Buttons-
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.
Web Page Validation-
PHP script must ensure that required fields are complete and submitted data is in
valid format.
PHP provides some inbuilt function using these functions that input data can be
validated.
empty() function will ensure that text field is not blank it is with some data, function
accepts a variable as an argument and returns TRUE when the text field is submitted
with empty string, zero, NULL or FALSE value.
Is numeric() function will ensure that data entered in a text field is a numeric value,
the function accepts a variable as an argument and returns TRUE when the text field
is submitted with numeric value.
<?php
if ($_SERVER['REQUEST_METHOD’] ===POST){
if(empty($_POST['name']))
{
echo "Name can't be blank<br/>";
}
if(!is_numeric($_POST['mobileno']))
{
echo "Enter valid Mobile Number<br/>";
}
$pattern=‘^b[\w.-]+@[w.-]+[A-Za-z]{2,6}\b/’;
if(!preg_match($pattern,$_POST['email']))
{
echo "Enter valid Email ID.<br/>";
}
}
?>
Superglobals
superglobals are predefined variables in PHP, 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.
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.
The superglobals are listed below.
Cookies -
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.
A cookie is a small file with the maximum size of 4KB that the web server stores on
the client computer.
There are three steps involved in identifying returning users :
1. Server script sends a set of cookies to the browser. For example: name, age or
identification number etc.
3. When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify the
user.
Use of Cookies
• When user requests for a page on a Web site data in the cookies which belongs
to a same site is send to the server automatically within the request.
• Expiration period of the cookies can be set, it can be set to seconds, minutes,
hours, days or for year, it can also be set a cookie to expire once browser
applications is closed.
PHP provides a inbuilt function setcookie(), that can send appropriate HTTP header
to create the cookie on the browser.
While creating the cookie, we have to pass require arguments with it.
Only name argument is must but it is better to pass value, expires and path to avoid
any ambiguity.
For Example : setcookie() is used to create a cookie storing the user name with name
"username", abc is the value stored in the cookie, expires argument uses PHP time()
function which returns current time, so the expiry time is 60 60 24 365 seconds after
the I current time, or one year in future, path argument is set to "/" it means that
cookies can be returned to any URL on the server, domain is set to abc.com, secure
flag is set to false and HttpOnly is too true.
We use the isset() function to find out if the cookie is set or not.
Modified cookie can be checked by calling the same cookie with its name to check
its modified value.
Delete Cookies –
Cookie can be deleted from user browser simply by setting expires
argument to any past date it will automatically delete the cookie from user browser.
Deleted cookie can be checked by calling the same cookie with its name to check if
it exists or not.
Example :
Accessing Cookie Value
For accessing a cookie value, the PHP $_COOKIE superglobal variable is used.
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Cookie Value = Vijay
Session -
Cookies are used to store user data on the client's browser is not the most secure
way of storing data, it can be easily hacked.
Cookie data for a website is uploaded every time a request is sent for specify URL on
a server. For example 10 cookies of a site is stored on a client browser then for every
request it has to upload 40KB of data for each request done from server as one
cookie is of 4KB.
Both this problem can be solved by using session to store user data
Session data is stored on the server side and each Session is assigned with a unique
Session ID (SID) for that session data.
As session data is stored on the server there is no need to send any data along with
the URL for each request to server.
More data can be stored in session as compared with cookie because location for
storing data is a server.
PHP stores the session data in a temporary file on the server,
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 -
Session are used to store important information such as the user id securely on
server where malicious users cannot temper them.
Sessions are the alternative to cookies on browsers that do not support cookies.
You are developing an application such as a shopping cart that has to temporary
store information with a capacity larger than 4KB.
Start Session -
If it is a new session then session_start() function will generate a unique SID for
the session or else a same function will be used to access existing along with the
data store in that session.
<?php
session_start();
?>
Set Session Variables -
Session variable can be set with a help of a PHP global variable: $_SESSION.
Data in the session is stored in the form of keys and values pair.
For example
<?php
session_start();
$_SESSION["username"]="abc";
?>
Get Session Variables -
Session variable can be get with a help of a PHP global variable: $_SESSION.
Example 1:
<?php
session_start();
echo "User name : "$_SESSION["username"];
?>
Output:
<?php
?>
Sending E-mail -
• PHP uses Simple Mail Transmission Protocol (SMTP) to send mail.
• Settings of the SMTP mail can be done through "php.ini" file present in the PHP
installation folder.
• Any text editor will be used to open and edit "php.ini"file.
• Locate [mail function] in the file.
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
We can get your SMTP settings from your web hosting providers.
If the server requires authentication, then add the following lines :
1. auth_username = [email protected]
2. auth_password = example_password
3. Save the new changes.
4. Restart server.
PHP Mail -
PHP mail is an inbuilt PHP function which is used to send emails from PHP scripts.
User's get contact you via email by providing a contact us form on the website that
emails the provided content.
It can also be used to send email, to your newsletter subscribers, password reset
links to users who forget their passwords, activation/confirmation links, registering
users and verifying their email addresses