Unit-3 PHP
Unit-3 PHP
Unit-3
[Web Application Development Using PHP]
Topic:
1. Form elements- TextBox, TextArea,Password,RadioButton, Check Box, Combo Box, Image
2. Buttons – Submit and Reset
3. Uploading File to web server
4. POST & GET method
5. PHP include and require statement
6. Basic of Cookie-Setting Cookies, Accessing Cookies, Deleting Cookies.
7. Basic of Session- Starting a Session, Destroying a session
✓ An HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.
✓ An HTML form facilitates the user to enter data that is to be sent to the server for
processing such as name, email address, password, phone number, etc.
✓ HTML forms are required if you want to collect some data from of the site visitor.
✓ For example: If a user wants to purchase some items on internet, he/she must fill the form
such as shipping address and credit/debit card details so that item can be sent to the given
address.
➢ Form Syntax
Note: The <form> element does not itself create a form but it is container to contain all
required form elements, such as <input>, <label>, etc.
➢ <input> element:
✓ The HTML <input> element is fundamental form element. It is used to create form fields,
to take input from user. We can apply different input filed to gather different information
form user. Following is the example to show the simple text input.
Example:
<body>
<form>
Enter your name <br>
<input type="text" name="username">
</form>
</body>
Output:
Created By :Professor Mr.Ravi Kukadiya Page 2
Shree Swaminarayan College Of Computer Science,Sardarnagar Bhavnagar
Unit-3
[Web Application Development Using PHP]
➢ TextField Control
✓ The type="text" attribute of input tag creates textfield control also known as single line
textfield control. The name attribute is optional, but it is required for the server side
component such as JSP, ASP, PHP etc.
Example:
<form>
First Name: <input type="text" name="firstname"/> <br/>
Last Name: <input type="text" name="lastname"/> <br/>
</form>
Output:
✓ Note: If you will omit 'name' attribute then the text filed input will not be submitted to
server.
✓ The <textarea> tag in HTML is used to insert multiple-line text in a form. The size of
<textarea> can be specify either using "rows" or "cols" attribute or by CSS.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<form>
Enter your address:<br>
<textarea rows="2" cols="20"></textarea>
</form>
</body>
</html>
Output:
Example:
<form>
<label for="gender">Gender: </label>
<input type="radio" id="gender" name="gender" value="male"/>Male
<input type="radio" id="gender" name="gender" value="female"/>Female <br/>
</form>
Output:
➢ Checkbox Control
✓ The checkbox control is used to check multiple options from given checkboxes.
<form>
Hobby:<br>
Output:
➢ Combobox Control:
✓ A select box, also called drop down box which provides option to list down various
options in the form of drop-down list, from where a user can select one or more options.
Example
✓ Here is example HTML code for a form with one drop down box
<!DOCTYPE html>
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>
</html>
Output:
➢ Image Button
✓ The image buttons in the HTML document can be created by using the type attribute of
an <input> element. Image buttons also perform the same function as submit buttons, but
the only difference between them is that you can keep the image of your choice as a
button.
Syntax
<input type="image" name="Name of image button" src="Path of the Image file? border
="Specfiy Image Border”>
Example:
<p>Sign in to your account:</p>
<div>
<label for="userId">User ID</label>
<input type="text" id="userId" name="userId" />
</div>
<input type="image" id="image" alt="Login" src="/media/examples/login-button.png"
/>
✓ The form-handler is typically a server page with a script for processing the input data.
✓ The form-handler is specified in the form's action attribute.
Syntax:
<input type="submit" name=”name of button” value=”value of button”>
Example
✓ An HTML form with two input fields; one text field and one submit button:
<form action="/action_page.php">
<label for="username">Username: </label>
<input type="text" id="username" name="username"><br>
<input type="submit" value="Submit">
</form>
Output:
Reset:
✓ The <input type="reset"> defines a reset button which resets all form values to its initial
values.
✓ Tip: Avoid reset buttons in your forms! It is frustrating for users if they click them by
mistake.
Syntax
<input type="reset" name=”Clear” value=”Rest”>
Output:
$target_path = "e:/";
$target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
echo "File uploaded successfully!";
} else{
echo "Sorry, file not uploaded, please try again!";
}
?>
❖ Write a php file to upload following Restriction
✓ Allow file types only .jpg,.jpeg and .png
✓ File shoud not be larger than 25kb
✓ After successfully upload display upload image in web page.
Example:
<?Php
$file_upload="true";
$file_up_size=$_FILES['file_up'][size];
echo $_FILES[file_up][name];
if ($_FILES[file_up][size]>250000)
{
$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file
size and then upload.<BR>";
$file_upload="false";
}
$file_name=$_FILES[file_up][name];
$add="upload/$file_name"; // the path with the file name where the file will be
stored
if($file_upload=="true"){
if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){
// do your coding here to give a thanks message or any other thing.
}else{echo "Failed to upload file Contact Site admin to fix the problem";}
}else{
echo $msg;
} ?>
1. GET method
2. POST method
✓ Get and Post methods are the HTTP request methods used inside the <form> tag to send form
data to the server.
✓ HTTP protocol enables the communication between the client and the server where a browser
can be the client, and an application running on a computer system that hosts your website
can be the server.
➢ GET method
✓ The GET method is used to submit the HTML form data. This data is collected by the
predefined $_GET variable for processing.
✓ The information sent from an HTML form using the GET method is visible to everyone in
the browser's address bar, which means that all the variable names and their values will be
displayed in the URL. Therefore, the get method is not secured to send sensitive information.
For Example
localhost/gettest.php?username=Harry&bloodgroup=AB+
✓ The bold part in the above URL is the variables name and italic part contains the values for
their corresponding variable.
✓ Note that only a limited amount of information can be sent using the GET method.
✓ With the help of an example, let's understand how the GET method works-
Example
✓ The below code will display an HTML form containing two input fields and a submit button.
In this HTML form, we used the method = "get" to submit the form data.
file: test1.html
<html>
<body>
<form action = "gettest.php" method = "GET">
Username: <input type = "text" name = "username" /> <br>
Blood Group: <input type = "text" name = "bloodgroup" /> <br>
<input type = "submit" />
</form>
</body>
</html>
✓ Create gettest.php file, which will accept the data sent by HTML form.
file: gettest.php
<html>
<body>
Welcome <?php echo $_GET["username"]; ?> </br>
Your blood group is: <?php echo $_GET["bloodgroup"]; ?>
</body>
</html>
✓ When the user will click on Submit button after filling the form, the URL sent to the server
could look something like this:
localhost/gettest.php?username=Harry&bloodgroup=AB-
✓ You can bookmark the page with the specific query string because the data sent by the GET
method is displayed in URL.
✓ GET requests can be cached.
✓ GET requests are always remained in the browser history.
➢ Disadvantages of GET Method
✓ The GET method should not be used while sending any sensitive information.
✓ A limited amount of data can be sent using method = "get". This limit should not exceed
2048 characters.
✓ For security reasons, never use the GET method to send highly sensitive information like
username and password, because it shows them in the URL.
✓ The GET method cannot be used to send binary data (such as images or word documents) to
the server.
➢ POST method
✓ Similar to the GET method, the POST method is also used to submit the HTML form data.
But the data submitted by this method is collected by the predefined superglobal
variable $_POST instead of $_GET.
✓ Unlike the GET method, it does not have a limit on the amount of information to be sent. The
information sent from an HTML form using the POST method is not visible to anyone.
For Example
localhost/posttest.php
✓ Note that the "post" method is more secure than the "get" method because the data sent using
the POST method is not visible to user.
With the help of an example, let's understand how the POST method works-
Example
✓ The below code will display an HTML form containing two input fields and a submit button.
In this HTML form, we used the method = "post" to submit the form data.
file: test2.html
<html>
<body>
<form action = "posttest.php" method = "post">
Username: <input type = "text" name = "username" /> <br>
Blood Group: <input type = "text" name = "bloodgroup" /> <br>
<input type = "submit" />
</form>
</body>
</html>
✓ Now create posttest.php file to accept the data sent by HTML form.
file: posttest.php
<html>
<body>
localhost/posttest.php
✓ Data security depends on the HTTP protocol because the information sent using the POST
method goes through the HTTP header. By using secure HTTP, you can ensure that your data
is safe.
➢ Disadvantages of POST Method
✓ POST requests do not cache.
✓ POST requests never remain in the browser history.
✓ It is not possible to bookmark the page because the variables are not displayed in URL.
✓ "PHP allows you to include file so that a page content can be reused many times. It is
very helpful to include files when you want to apply the same HTML or PHP code to
multiple pages of a website." There are two ways to include file in PHP.
1. include
2. require
➢ Both include and require are identical to each other, except failure.
✓ include only generates a warning, i.e., E_WARNING, and continue the execution of the
script.
✓ require generates a fatal error, i.e., E_COMPILE_ERROR, and stop the execution of the
script.
➢ Advantage
✓ Code Reusability: By the help of include and require construct, we can reuse HTML
code or PHP script in many PHP scripts.
✓ Easy editable: If we want to change anything in webpages, edit the source file included
in all webpage rather than editing in all the files separately.
➢ PHP include
✓ PHP include is used to include a file on the basis of given path. You may use a relative or
absolute path of the file.
Syntax
Examples
✓ Let's see a simple PHP include example.
File: menu.html
<a href="home.php">Home</a> |
<a href="php_std.php">PHP</a> |
<a href="java_std.php">Java</a> |
<a href="html_std.php">HTML</a>
File: include1.php
<?php include("menu.html"); ?>
<h1>This is Main Page</h1>
Output:
Home |
PHP |
Java |
HTML
This is Main Page
➢ PHP require
✓ PHP require is similar to include, which is also used to include files. The only difference
is that it stops the execution of script if the file is not found whereas include doesn't.
Syntax
Examples
✓ Let's see a simple PHP require example.
File: menu.html
<a href="home.php">Home</a> |
<a href="php_std.php">PHP</a> |
<a href="java_std.php">Java</a> |
<a href="html_std.php">HTML</a>
File: require1.php
Output:
Home |
PHP |
Java |
HTML
This is Main Page
Example
include.php
<?php
//include welcome.php file
include("welcome.php");
echo "The welcome file is included.";
?>
Output:
✓ The welcome.php file is not available in the same directory, which we have included. So,
it will produce a warning about that missing file but also display the output.
Warning: include(welcome.php): failed to open stream: No such file or directory in
C:\xampp\htdocs\program\include.php on line 3
Output:
✓ In case of require() if the file (welcome.php) is not found in the same directory. The
require() will generate a fatal error and stop the execution of the script, as you can see in
the below output.
HELLO
Warning: require(Welcome.php): failed to open stream: No such file or directory in
C:\xampp\htdocs\program\include.php on line 3
Fatal error: require(): Failed opening required 'Welcome.php' (include_path='C:\xampp
o Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
o Browser stores this information on local machine for future use.
o 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.
o This chapter will teach you how to set cookies, how to access them and how to delete
them.
o The Anatomy of a Cookie
o Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser). A PHP script that sets a cookie might send headers that look
something like this –
HTTP/1.1 200 OK
✓ A PHP script will then have access to the cookie in the environmental variables
$_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values.
Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].
✓ 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.
setcookie(name, value, expire, path, domain, security);
o Name − This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
o Value − This sets the value of the named variable and is the content that you actually
want to store.
o Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then cookie
will automatically expire when the Web Browser is closed.
o Path − This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
o Domain − This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
o Security − 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.
✓ Following example will create two cookies name and age these cookies will be expired
after one hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
✓ PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in
above example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
</body>
</html>
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
✓ Officially, to delete a cookie you should call setcookie() with the name argument only but
this does not always work well, however, and should not be relied on.
✓ It is safest to set the cookie with a date that has already expired −
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
✓ When a PHP script wants to retrieve the value from a session variable, PHP automatically
gets the unique session identifier string from the PHPSESSID cookie and then looks in its
temporary directory for the file bearing that name and a validation can be done by
comparing both values.
✓ A session ends when the user loses the browser or after leaving the site, the server will
terminate the session after a predetermined period of time, commonly 30 minutes
duration.
<?php
session_start();
✓ The htmlspecialchars() may be used when printing the SID in order to prevent XSS
related attacks.