0% found this document useful (0 votes)
28 views18 pages

PHP Unit 3 Econtent

UNIT-III Working with Forms: Creating Forms, Accessing Form Input with User defined Arrays, Combining HTML and PHP code on a single Page, Using Hidden Fields to save state, Redirecting the user, Sending Mail on Form Submission, and Working with File Uploads, Managing files on server, Exception handling.

Uploaded by

varaprasadpgtcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views18 pages

PHP Unit 3 Econtent

UNIT-III Working with Forms: Creating Forms, Accessing Form Input with User defined Arrays, Combining HTML and PHP code on a single Page, Using Hidden Fields to save state, Redirecting the user, Sending Mail on Form Submission, and Working with File Uploads, Managing files on server, Exception handling.

Uploaded by

varaprasadpgtcs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

D.N.R.

COLLEGE (AUTONOMOUS): BHIMAVARAM


DEPARTMENT OF COMPUTER SCIENCE

Web Applications Development using


PHP& MYSQL -7A
V SEMESTER
UNIT III
WEB APPLICATIONS DEVELOPMENT USING PHP & MYSQL
UNIT III
WORKING WITH FORMS
HTML FORM: HTML form is a section of a document which contains controls such as text fields,
password fields, checkboxes, radio buttons, submit button, menus etc.
<form> is a HTML element to collect input data with containing interactive controls. It provides
facilities to input text, number, values, email, password, and control fields such as checkboxes, radio
buttons, submit buttons, etc., or in other words, form is a container that contains input elements like text,
email, number, radio buttons, checkboxes, submit buttons, etc.
Syntax:
<form>
<!--form elements-->
</form>
The <form> element is a container for different types of input elements, such as: text fields, checkboxes,
radio buttons, submit buttons, etc.
FORM ELEMENTS: These are the following HTML <form> elements:
1. <label>: It defines label for <form> elements.
2. <input>: It is used to get input data from the form in various types such as text, password, email,
etc by changing its type.
3. <button>: It defines a clickable button to control other elements or execute a functionality.
4. <select>: It is used to create a drop-down list.
5. <textarea>: It is used to get input long text content.
6. <fieldset>: It is used to draw a box around other form elements and group the related data.
7. <legend>: It defines caption for fieldset elements.
8. <datalist>: It is used to specify pre-defined list options for input controls.
9. <output>: It displays the output of performed calculations.
10. <option>: It is used to define options in a drop-down list.
11. <optgroup>: It is used to define group-related options in a drop-down list.
HTML <input> ELEMENTS: The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on the type attribute.
Here are some examples:

Department of Computer Science Web Applications Development using PHP& MYSQL Page 1
Type Description

<input type="text"> Displays a single-line text input field

<input type="radio"> Displays a radio button (for selecting one of many choices)

<input type="checkbox"> Displays a checkbox (for selecting zero or more of many choices)

<input type="submit"> Displays a submit button (for submitting the form)

<input type="button"> Displays a clickable button

Example:
<HTML>
<head>
<title>REGISTRATION FORM</title>
</head>
<body>
<form action="action_page.php">
<h1 align="center"> REGISTRATION FORM </h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="FullName"><b>Full Name</b></label>
<input type="text" name="Enter your Full Name" name="FullName" required>
<label for="email"><b>Email</b></label>
<input type="text" mail="Enter Email" name="email" required>
<label for="password"><b>Password</b></label>
<input type="password" password="Enter Password" name="password" required>
<label for="password-repeat"><b>Repeat Password</b></label>
<input type="password" password="Repeat Password" name="password-repeat" required>
<hr>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<button type="submit" class="Register Button">Register</button>
</div>
<p>Already have an account? <a href="#">Sign in</a>.</p>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 2
</div>
</form>
</body>
</html>

OUTPUT:

CREATING REGISTRATION FROM:


<HTML>
<head>
<title>REGISTRATION FORM</title>
</head>
<body bgcolor="CadetBlue">
<form action="action_page.php">
<h1 align="center"> REGISTRATION FORM </h1>
<p>Please fill in this form to create an account.</p>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 3
<hr>
<label for="FullName"><b>Full Name</b></label>
<input type="text" name="Enter your Full Name" name="FullName" required>
<label for="email"><b>Email</b></label>
<input type="text" mail="Enter Email" name="email" required>
<label for="password"><b>Password</b></label>
<input type="password" password="Enter Password" name="password" required>
<label for="password-repeat"><b>Repeat Password</b></label>
<input type="password" password="Repeat Password" name="password-repeat" required>
<hr>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<button type="submit" class="Register Button">Register</button>
</div>
<p>Already have an account? <a href="#">Sign in</a>.</p>
</div>
</form>
</body>
</html>
OUTPUT:

Department of Computer Science Web Applications Development using PHP& MYSQL Page 4
COMBINING HTML AND PHP CODE ON A SINGLE PAGE: PHP code is normally mixed with
HTML tags. PHP is an embedded language, meaning that you can jump between raw HTML code and PHP
without sacrificing readability. If we want to use PHP in the Html document, then we have to follow the steps
which are given below. Using these simple steps, we can easily add the PHP code.
Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in the text
editor in which we want to use the PHP.
<!Doctype Html>
<html>
<head>
<title>
Use a Php in Html
</title>
</head>
<body>
</body>
</html>
Step 2: Now, we have to place the cursor in any tag of the <body> tag where we want to add the code of
PHP. And, then we have to type the start and end tag of PHP.
<h1>
<?php ?>
</h1>
Step 3: After then, we have to type the code of PHP between the tags of PHP.
<h1>
<?php
echo " This is example program for combining HTML and PHP "
?>
</h1>
Step 4: When we successfully add the PHP code, then we have to save the Html file and then run the file in
the browser.
<!doctype html>
<html>
<head>
<title>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 5
Use a Php in Html
</title>
</head>
<body>
<h1>
<?php
echo " This is example program for combining HTML and PHP "
?>
</h1>
</body>
</html>

OUTPUT:

SENDING MAIL ON FORM SUBMISSION: PHP makes use of mail() function to send an email. This
function requires three mandatory arguments that specify the recipient's email address, the subject of the
message and the actual message additionally there are other two optional parameters.
Syntax: mail( to, subject, message, headers, parameters );

Department of Computer Science Web Applications Development using PHP& MYSQL Page 6
Sr.No Parameter & Description

1 to
Required. Specifies the receiver / receivers of the email

2 subject
Required. Specifies the subject of the email. This parameter cannot contain any
newline characters

3 message
Required. Defines the message to be sent. Each line should be separated with a
LF (\n). Lines should not exceed 70 characters

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

5 parameters
Optional. Specifies an additional parameter to the send mail program

As soon as the mail function is called PHP will attempt to send the email then it will return true if successful
or false if it is failed. Multiple recipients can be specified as the first argument to the mail() function in a
comma separated list.
FILE UPLOADS: PHP allows you to upload single and multiple files through few lines of code only. PHP
file upload features allow you to upload binary and text files both.
PHP $_FILES: The PHP global $_FILES contains all the information of file. By the help of $_FILES
global, we can get file name, file type, file size, temp file name and errors associated with file.
PHP would create following five variables −
 $_FILES['file']['tmp_name'] − the uploaded file in the temporary directory on the web server.
 $_FILES['file']['name'] − the actual name of the uploaded file.
 $_FILES['file']['size'] − the size in bytes of the uploaded file.
 $_FILES['file']['type'] − the MIME type of the uploaded file.
 $_FILES['file']['error'] − the error code associated with this file upload.
The process of uploading a file follows these steps −

Department of Computer Science Web Applications Development using PHP& MYSQL Page 7
 The user opens the page containing a HTML form featuring a text files, a browse button and a submit
button.
 The user clicks the browse button and selects a file to upload from the local PC.
 The full path to the selected file appears in the text filed then the user clicks the submit button.
 The selected file is sent to the temporary directory on the server.
 The PHP script that was specified as the form handler in the form's action attribute checks that the file
has arrived and then copies the file into an intended directory.
 The PHP script confirms the success to the user.
PHP File Upload Example
File: uploadform.html
<form action="uploader.php" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" value="Upload Image" name="submit"/>

</form>
File: uploader.php
<?php
$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!";
}
?>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 8
Output:

Department of Computer Science Web Applications Development using PHP& MYSQL Page 9
WORKING WITH COOKIES AND USER SESSIONS
INTRODUCING 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. Such way, cookie can be received at the server side.

There are three steps involved in identifying returning users −


 Server script sends a set of cookies to the browser. For example name, age, or identification number
etc.
 Browser stores this information on local machine for future use.
 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.
COOKIES IN PHP: 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.

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.
Syntax: setcookie(name, value, expire, path, domain, security);

Department of Computer Science Web Applications Development using PHP& MYSQL Page 10
Here is the detail of all the arguments −
 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.
 Value − This sets the value of the named variable and is the content that you actually want to store.
 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.
 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.
 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.
 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.
PHP Cookie Example
File: cookie1.php
<?php
setcookie("user", "Sreenu");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"]))
{
echo "Sorry, cookie is not found!";
}
else
{
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>

Department of Computer Science Web Applications Development using PHP& MYSQL Page 11
Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
Cookie Value: Sreenu
ADVANTAGES OF 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. Such way, cookie can be
received at the server side.
Advantages:
1. Storing cookies is lighter as it does not puts extra load on the server. It is generally stored on a client
machine.
2. Cookies are simple to use and implement.
3. A cookie can be configured easily.
4. Using cookies, it can be used to store session information like pages or threads etc.
5. Cookies, once stored, could be used later also without creating cookies.
6. Cookies are used to personalize user preferences.
7. Based on user preferences, cookies could be used to show similar types of advertisements to a user.
DISADVANTAGES OF COOKIES
 A cookie is not recommended to store data that needs to be secured. Content in cookies is plain text
once only those data could be stored, which is not security concerned.
 Encrypting and decrypting cookies data is not meaningful as it required extra coding leading to
resource extra responsibilities.
 A cookie can store a maximum of 4 KB of data; hence it cannot be used to store large data.
 Cookies from advertisements sites could track user personal information like browsing preferences.
 Users can delete a cookies.
 Cookies will not work if the security level is set to high in the browser.
 User has the option of disabling cookies on his computer from browser’s setting .
SESSION INTRODUCTION: When we work with an application, we open it, do some changes, and then
we close it. This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 12
Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the browser. So
Session variables hold information about one single user, and are available to all pages in one application.
PHP SESSION: PHP session is used to store and pass information from one page to another temporarily
(until user close the website). Session identifiers or SID is a unique number which is used to identify every
user in a session based environment. The SID is used to link the user with his information on the server
like posts, emails etc. 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_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
bool session_start (void)

Example
session_start();
PHP $_SESSION: PHP $_SESSION is an associative array that contains all session variables. It is used to
set and get session variable values.
Example: Store information
$_SESSION["user"] = "Sachin";
Example: Get information
echo $_SESSION["user"];
PHP Session Example
//Save file as session1.php
<?php
session_start();

Department of Computer Science Web Applications Development using PHP& MYSQL Page 13
?>
<html>
<body>
<?php
$_SESSION["user"] = "DNR";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body>
</html>
//Save file as session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>
OUTPUT:

Department of Computer Science Web Applications Development using PHP& MYSQL Page 14
ADVANTAGES OF SESSION: PHP session is used to store and pass information from one page to
another temporarily (until user close the website).
Advantages:
1. It is easy to implement.
2. It ensures data durability, since session state retains data even if ASP.NET work process restarts as data in
3. Session State is stored in other process space.
4. It works in the multi-process configuration, thus ensures platform scalability.
5. It helps to maintain user states and data to all over the application.
6. It can easily be implemented and we can store any kind of object.
7. Stores every client data separately.
8. Session is secure and transparent from user.
DISADVANTAGES OF SESSION:
1. Performance overhead in case of large volume of user, because of session data stored in server
memory.
2. Overhead involved in serializing and De-Serializing session Data. because In case of StateServer and
SQLServer session mode we need to serialize the object before store.
3. With the use of Session state, it will affect the performance of memory, because session state variable
stays in memory until we destroy the state.
4. If the worker process or application domain recycles all session data will be lost.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 15
DIFFERNCES BETWEEN COOKIES AND SESSIONS:
COOKIE SESSION
Cookies are client-side files on a local computer that Sessions are server-side files that contain user data.
hold user information.
Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the
programmed, the session is over.
It can only store a certain amount of info. It can hold an indefinite quantity of data.
The browser’s cookies have a maximum capacity of We can keep as much data as we like within a
4 KB. session, however there is a maximum memory
restriction of 128 MB that a script may consume at
one time.
Because cookies are kept on the local computer, we To begin the session, we must use the session start()
don’t need to run a function to start them. method.
Cookies are not secured. Session are more secured compare than cookies.
Cookies stored data in text file. Session save data in encrypted form.
Cookies stored on a limited data. Session stored a unlimited data.
In PHP, to get the data from Cookies , $_COOKIES In PHP , to get the data from Session, $_SESSION
the global variable is used the global variable is used
We can set an expiration date to delete the cookie’s In PHP, to destroy or remove the data stored within
data. It will automatically delete the data at that a session, we can use the session_destroy() function,
specific time. and to unset a specific variable, we can use the
unset() function.

Department of Computer Science Web Applications Development using PHP& MYSQL Page 16
Department of Computer Science Web Applications Development using PHP& MYSQL Page 17

You might also like