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, Working with File Uploads. Working with Cookies and User
Sessions: Introducing Cookies, Setting a Cookie with PHP, Session Function
Overview, Starting a Session, Working with session variables, passing session
IDs in the Query String, Destroying Sessions and Unsetting Variables, Using
Sessions in an Environment with Registered Users.
Q) What is the
Form?
Forms are used to get input from the user and submit it to the web
server for processing. The diagram below illustrates the form handling
process.
A form is an HTML tag that contains graphical user interface items
such as input box, check boxes radio buttons etc. The form is defined using the
<form>...</form> tags and GUI items are defined using form elements
such as input.
PHP Form Methods:
1. PHP POST
method: This is the built-in PHP super global
array variable that is used to get values submitted via HTTP POST method.
Syntax:
<?php
$_POST['variable_name'];
?>
2.
PHP GET method: This is the built-in PHP super global
array variable that is used to get values submitted via HTTP GET method.
Syntax:
<?php
$_GET['variable_name'];
?>
Example:
<html>
<head><title>A simple HTML form</title></head>
<body>
<form
method=”post” action=”send_simpleform.php”>
<p><label
for=”user”>Name:</label><br/>
<input
type=”text” id=”user” name=”user”></p>
<p><label
for=”message”>Message:</label><br/>
<textarea
id=”message” name=”message” rows=”5” cols=”40”> </textarea></p>
<button
type=”submit” name=”submit” value=”send”>Send Message</button>
</form>
</body> </html>
NOTE: Save
this file as simpleform.html
Reading Input from a Form
<html>
<head>
<title>A
simple response</title>
</head>
<body>
<p>Welcome,
<strong><?php echo $_POST[‘user’]; ?></strong>!</p>
<p>Your
message is: <strong><?php echo $_POST[‘message’]; ?></strong></p>
</body>
</html>
NOTE: Save this file
as send_simpleform.php
Q) How to Accessing
Form Input with User-Defined Arrays
Text fields, text areas, and radio buttons elements can submit a
single value per element name, but when working with elements such as
checkboxes where the user can choose one or more items. This behavior can
change using user-defined arrays.
<select name="products" multiple>
These elements make it possible for the user to choose multiple
items. If we name the SELECT element with a plain name the script
that receives this data will only have access to a single value corresponding
to this name. We can change this behavior by renaming any elements of this kind
so that its name ends with an empty set of square brackets
<select name="products[]" multiple>
Example:
<html><head><title> An HTML form including a SELECT element</title></head>
<body>
<form action="list.php" method="POST">
<input type="text" name="user">
<br>
<textarea name="address" rows="5" cols="40">
</textarea>
<br>
<select name="products[]" multiple>
<option>Sonic Screwdriver
<option>Tricorder
<option>ORAC AI
<option>HAL 2000
</select>
<br>
<input type="submit" value="hit it!">
</form></body></html>
Q) How to Combined
HTML and PHP Code on a Single Page
If you want to insert
PHP code into an HTML file, just write the PHP anywhere you want so long as
they're inside the PHP tags. Open a PHP tag with <?php and then close it
with ?>
Example:
<html>
<title>HTML with PHP</title>
<body>
<h1>My Example</h1>
<?php
//your PHP code goes here
?>
<b>Here is some more HTML</b>
<?php
//more PHP code
?>
</body>
</html>
Q) How to Use
Hidden Fields to Save State.
A hidden field behaves the same as a text field, except that the
user cannot see it unless he views the HTML source of the document that
contains it.
Finally, before the HTML code for the form submission button, add
the hidden field. This field saves the incremented value of $num_tries:
<input type=”hidden”
name=”num_tries” value=”<?php echo $num_tries; ?>”/>
Example:
<?php
$num_to_guess = 42;
$num_tries
= (isset($_POST[‘num_tries’])) ? $num_tries + 1 : 1;
if (!isset($_POST[‘guess’])) {
$message = “Welcome to the guessing machine!”;
} elseif (!is_numeric($_POST[‘guess’])) { //
is not numeric
$message = “I don’t understand that
response.”;
} elseif ($_POST[‘guess’] == $num_to_guess) {
// matches!
$message = “Well done!”;
} elseif ($_POST[‘guess’] > $num_to_guess)
{
$message = $_POST[‘guess’].” is too big! Try a
smaller number.”;
} elseif ($_POST[‘guess’] < $num_to_guess)
{
$message = $_POST[‘guess’].” is too small! Try
a larger number.”;
} else { // some other condition
$message = “I am terribly confused.”;
}
?>
<html>
<head>
<title>A
PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p><strong>Guess
number:</strong> <?php echo $num_tries; ?></p>
<form
action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”POST”>
<p><label
for=”guess”>Type your guess here:</label><br/>
<input
type=”text” id=”guess” name=”guess” /></p>
<input
type=”hidden” name=”num_tries” value=”<?php echo $num_tries; ?>”/>
<button
type=”submit” name=”submit” value=”submit”>Submit</button>
</form>
</body>
</html>
Q) How to Redirecting
the User
When a server script communicates with a client, it must first send
some headers that provide information about the document to follow. PHP usually
handles this for you automatically, but you can choose to send your own header
lines with PHP’s header() function.
To call the header() function, you must be absolutely sure that no
output has been sent to the browser. The first time content is sent to the
browser, PHP sends out headers of its own, and it’s too late for you to send
any more. Any output from your document, even a line break or a space outside
your script tags, causes headers to be sent. If you intend to use the header()
function in a script, you must make certain that nothing precedes the PHP code
that contains the function call. You should also check any libraries that you
might be using.
The below code shows typical headers sent to the browser by PHP,
beginning with line 3, in response to the request in line 1.
1:
HTTP/1.1 200 OK
2: Date:
Sun, 29 Jan 2012 15:50:28 PST
3:
Server: Apache/2.2.21 (Win32) PHP/5.4.0
4:
X-Powered-By: PHP/5.4.0
5:
Connection: close
6:
Content-Type: text/html
By sending a Location header rather than PHP’s default header, you
can cause the browser to be redirected to a new page, such as the following:
header(“Location: http://www.samspublishing.com”);
Example that Using header() to
Redirect User
<?php
$num_to_guess
= 42;
$num_tries
= (isset($_POST[‘num_tries’])) ? $num_tries + 1 : 1;
if
(!isset($_POST[‘guess’])) {
$message
= “Welcome to the guessing machine!”;
} elseif
(!is_numeric($_POST[‘guess’])) { // is not numeric
$message
= “I don’t understand that response.”;
} elseif
($_POST[‘guess’] == $num_to_guess) { // matches!
header(“Location:
congrats.html”);
exit;
} elseif
($_POST[‘guess’] > $num_to_guess) {
$message
= $_POST[‘guess’].” is too big! Try a smaller number.”;
} elseif
($_POST[‘guess’] < $num_to_guess) {
$message = $_POST[‘guess’].” is too small! Try
a larger number.”;
} else {
// some other condition
$message
= “I am terribly confused.”;
}
?>
<html>
<head>
<title>A
PHP number guessing script</title>
</head>
<body>
<h1><?php
echo $message; ?></h1>
<p><strong>Guess
number:</strong> <?php echo $num_tries; ?></p>
<form
action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”POST”>
<p><label
for=”guess”>Type your guess here:</label><br/>
<input type=”text” id=”guess” name=”guess”
/></p>
<input
type=”hidden” name=”num_tries” value=”<?php echo $num_tries; ?>”/>
<button
type=”submit” name=”submit” value=”submit”>Submit</button>
</form>
</body>
</html>
Q)How to Sending
Mail on Form Submission.
Before sending mail, the system is should properly configured.
This can be done using mail( ) function. Before the use of mail() function to
send mail, it need to set up a few directives in the php.ini file so that the
function works properly. Open php.ini with a text editor and look for these
lines:
[mail
function]
; For
Win32 only.
;
http://php.net/smtp
SMTP =
localhost
;
http://php.net/smtp-port
smtp_port
= 25
; For
Win32 only.
;
http://php.net/sendmail-from
;sendmail_from
= me@example.com
; For
Unix only. You may supply arguments as well (default: “sendmail -t -i”).
;
http://php.net/sendmail-path
;sendmail_path
=
If you’re using Windows as your web server platform, the first two
directives apply to it. For the mail() function to send mail, it must be able
to access a valid outgoing mail server. If you plan to use the outgoing mail
server of your choosing, the entry in php.ini could look like this:
SMTP = smtp.yourisp.net
The second configuration directive is sendmail_from, which is the
email address used in the From header of the outgoing email. It can be
overwritten in the mail script itself but normally operates as the default
value, as in this example:
sendmail_from = youraddress@yourdomain.com
A good rule of thumb for Windows users is that whatever outgoing
mail server you’ve set up in your email client on that machine, you should also
use as the value of SMTP in php.ini.
If your web server is running on a Linux/UNIX platform, you use
the sendmail functionality of that particular machine. In this case, only the
last directive applies to you: sendmail_path. The default is sendmail
-t -i, but if sendmail is in an odd place or if you need to specify
different arguments, feel free to do so, as in the following example, which
does not use real values:
sendmail_path = /opt/sendmail -odd
-arguments
After making any changes to php.ini on any platform, you must
restart the web server process for the changes to take effect.
Example: Creating a Simple Feedback
Form
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title>E-Mail Form</title>
5: </head>
6: <body>
7: <form action=”sendmail.php” method=”POST”>
8: <p><label
for=”name”>Name:</label><br/>
9: <input type=”text” size=”25” id=”name”
name=”name”/></p>
10: <p><label for=”email”>E-Mail
Address:</label><br/>
11: <input type=”text” size=”25” id=”email”
name=”email”/></p>
12: <p><label
for=”msg”>Message:</label><br/>
13: <textarea id=”msg” name=”msg” cols=”30”
rows=”5”></textarea></p>
14: <button type=”submit” name=”submit”
value=”send”>Send Message</button>
15: </form>
16: </body>
17: </html>
Creating the Script to Send the Mail
1:<?php
2: //start building the mail string
3: $msg = “Name: “.$_POST[‘name’].”\n”;
4: $msg .= “E-Mail: “.$_POST[‘email’].”\n”;
5: $msg .= “Message: “.$_POST[‘message’].”\n”;
6:
7: //set up the mail
8: $recipient = “you@yourdomain.com”;
9: $subject = “Form Submission Results”;
10: $mailheaders = “From: My Web Site
<defaultaddress@yourdomain.com> \n”;
11: $mailheaders .= “Reply-To: “.$_POST[‘email’];
12:
13: //send the mail
14: mail($recipient, $subject, $msg, $mailheaders);
15: ?>
16: <!DOCTYPE html>
17: <html>
18: <head>
19: <title>Sending mail from the form in
Listing 11.10</title>
20: </head>
21: <body>
22: <p>Thanks, <strong><?php echo $_POST[‘name’];
?></strong>,
23: for your message.</p>
24: <p>Your e-mail address:
25: <strong><?php echo $_POST[‘email’];
?></strong></p>
26: <p>Your message: <br/> <?php echo
$_POST[‘message’]; ?> </p>
27: </body>
28: </html>
Q) Explain the Working with File Uploads
PHP makes available to deal with web browsers
support file uploads of input.
Information about the uploaded file becomes
available in the $_FILES superglobal, which is indexed by the name of the
upload field (or fields) in the form. The corresponding value for each of these
keys is an associative array. These fields are described in Table, using
fileupload as the name of the form field used for the upload.
A Simple File
Upload Form
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title>A simple file upload form</title>
5: </head>
6: <body>
7: <form action=”do_upload.php”
enctype=”multipart/form-data” method=”POST”>
8: <input type=”hidden” name=”MAX_FILE_SIZE”
value=”1048576” />
9: <p><label for=”fileupload”>File to
Upload:</label>
10: <input type=”file” id=”fileupload”
name=”fileupload” /></p>
11: <button type=”submit” name=”submit”
value=”send”>Upload File</button>
12: </form>
13: </body>
14: </html>
A File Upload
Script
1: <?php
2: $file_dir = “/path/to/upload/directory”;
3:
4: foreach($_FILES as $file_name => $file_array) {
5: echo “path: “.$file_array[‘tmp_name’].”<br/>\n”;
6: echo “name: “.$file_array[‘name’].”<br/>\n”;
7: echo “type: “.$file_array[‘type’].”<br/>\n”;
8: echo “size: “.$file_array[‘size’].”<br/>\n”;
9:
10: if (is_uploaded_file($file_array[‘tmp_name’])) {
11: move_uploaded_file($file_array[‘tmp_name’],
12: “$file_dir/”.$file_array[‘name’])
13: or die (“Couldn’t move file”);
14: echo “File was moved!”;
15: } else {
16: echo “No file found.”;
17: }
18: }
19: ?>
Q) Explain briefly about cookies in PHP.
Cookies are text files stored on the client computer and they are
kept of use tracking purpose. A single host can request that up to 20 cookies be stored
by a user’s browser. Each cookie consists of a name, value, and expiration
date, as well as host and path information. The size of an individual cookie is
limited to 4KB.
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.
Q) How to Set a Cookie with PHP.
A cookie is created with the
setcookie() function. This function requires upto six arguments and should be
called before <html> tag. For each cookie this function has to be called
separately.
Syntax
<?php
setcookie(cookie_name, cookie_value, [expiry_time],
[cookie_path], [domain], [secure], [httponly]);
?>
HERE,
- “setcookie” is the PHP function used to create the cookie.
- “cookie_name” is the name of the cookie that the server will use when retrieving its value from the $_COOKIE array variable. It’s mandatory.
- “cookie_value” is the value of the cookie and its mandatory
- “[expiry_time]” is optional; it can be used to set the expiry time for the cookie such as 1 hour. The time is set using the PHP time() functions plus or minus a number of seconds greater than 0 i.e. time() + 3600 for 1 hour.
- “[cookie_path]” is optional; it can be used to set the cookie path on the server. The forward slash “/” means that the cookie will be made available on the entire domain. Sub directories limit the cookie access to the subdomain.
- “[domain]” is optional, it can be used to define the cookie access hierarchy i.e. www.cookiedomain.com means entire domain while www.sub.cookiedomain.com limits the cookie access to www.sub.cookiedomain.com and its sub domains.
- “[secure]” is optional, the default is false. It is used to determine whether the cookie is sent via https if it is set to true or http if it is set to false.
- “[Httponly]” is optional. If it is set to true, then only client side scripting languages i.e. JavaScript cannot access them.
Note: the php set cookie function must be executed before
the HTML opening tag.
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>
Q) How to access and delete Cookies in PHP
1. Accessing Cookies with PHP: 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 />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
</body> </html>You can use isset() function to check if a cookie is set or not.
<html> <head> <title>Accessing Cookies with PHP</title> </head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body> </html>
2. Deleting Cookie with PHP: To delete a cookie you should call setcookie() with the name argument only .
<?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>
Q) Write a note on session.
PHP session is a way of storing information
in session variables, which could be used across multiple web pages for
authentication. Unlike a cookie, the information is not stored on the user’s
computer instead a session creates a file on the server, in a temporary
directory, where it stores information in session variables. This stored
information for a session will be available to all the web pages on the site
during navigation. On the server, the location of a temporary file is
determined by a setting in the php.ini file called session.save_path.
PHP session when created, it involves the following three steps.
- When a session is created, PHP generates a unique session identifier, which is a random string of 32 hexadecimal numbers. A session id resembles somethinglike this 9c8foj87c3jj973actop1re472e8774.
- Server sends a cookie known as PHPSESSID to the user’s machine to store unique session identification string.
- The Server will generate a file in a designated temporary directory that has the name of the unique session identifier prefixed by sess _g. sess_9c8foj87c3jj973actop1re472e8774.
Q) How to Starting a PHP Session.
A PHP session is started or created with the session_start () function and
is destroyed with the session_destroy () function. A PHP global variable, known
as $_SESSION, is used to set values to session variables. We can unset all
values set to session variables using the session_unset () function.
|
SYNTAX
|
DESCRIPTION
|
|
session_start();
|
It is an in-built function used to create a PHP session.
|
|
session_destroy();
|
It is an in-built function used to destroy a PHP session.
|
|
session_unset();
|
It is an in-built function used to unset all session variables. It is
triggered before the session_destroy () function.
|
|
isset ();
|
It is an in-built function to check if session variable is already set or
not.
|
|
$_SESSION
|
It is a PHP global variable that is used to set values to Session
variables. E.g. $_SESSION[“userID”] = “php_user”;
|
|
print_r($_SESSION)
|
It will print the complete array of the session variables and their
values.
|
Q) Explain the working with Session variables.
We are be going
to do the following operations using PHP session variables.
- Start a PHP Session and set Session Variables: A new PHP session starts with the session_start () function. Once a session is created, then we can set values for the session variables using the PHP global variable: $_SESSION as shown below. Here, we have set the values for the session variables “userID” as “php_user” and “password” as “tutorials”
<?php
session_start();
?>
<html>
<head> <title>PHP
Session - Create</title>
</head>
<body>
<?php
$_SESSION["userID"] = "php_user";
$_SESSION["password"] = "tutorials";
echo "<br>PHP Session is established and session
variables are set successfully!";
?>
</body> </html>
·
Retrieve
PHP Session Variables values: We can retrieve the values of the session variables that we set
last time after creating PHP session. When we open PHP session at the beginning
of each page (session_start ()) should be written as shown below. Here, we are
retrieving and echoing those values using the global $_SESSION variable.
<?php
// Start the PHP session
session_start();
?>
<html>
<head> <title>PHP
Session - Retrieve</title>
</head>
<body>
<?php
// Echo PHP session variables that were set before on previous
page
echo "User ID is " . $_SESSION["userID"] .
".<br><br>";
echo "Password is " . $_SESSION["password"] .
".";
?>
</body> </html>
·
Update
PHP Session Variables values: We can update the values of the session variables in the same
session by overwriting the existing values of those variables as shown below.
As explained earlier, before we start updating the values of the session
variables, we need to open a PHP session at the beginning of each page
(session_start ()). Here, we have updated the values for the session variables
“userID” as “new_php_user” and “password” as “education”.
<?php
// Start the PHP session
session_start();
?>
<html>
<head> <title>PHP
Session - Modify</title>
</head>
<body>
<?php
// Set PHP session variables
$_SESSION["userID"] = "new_php_user";
$_SESSION["password"] = "education";
echo "PHP Session variables are modified
successfully!<br><br>";
print_r($_SESSION);
?>
</body>
</html>
Q) How to Destroy a PHP Session and unset
all Session Variables values.
1.
session_destroy () function is used to destroy the
current session.
2.
session_unset () function is used unset the values
for all the PHP session variables.
Example:
<?php
session_start();
?>
<html>
<head> <title>PHP
Session - Destroy</title>
</head>
<body>
<?php
session_unset();
print_r($_SESSION);
session_destroy();
echo "<br><br>PHP Session is destroyed
successfully and all session variables are removed!<br><br>";
?>
</body> </html>
Q) Using Sessions in an Environment with
Registered Users
Suppose that you’ve created an online
community, or a portal, or some other type of application that users can
“join.” The process usually involves a registration form, where the user
creates a username and password and completes an identification profile.
From that point forward, each time a
registered user logs in to the system, you can grab the user’s identification
information and store it in the user’s session.
The items you decide to store in the user’s
session should be those items you can imagine using quite a bit—and that would
be inefficient to continually extract from the database.
For example, suppose that you have created a
portal in which users are assigned a certain level, such as administrator,
registered user, anonymous guest, and so forth. Within your display modules,
you would always want to check to verify that the user accessing the module has
the proper permissions to do so.
Thus, “user level” is an example of a value
stored in the user’s session, so that the authentication script used in the
display of the requested module only has to check a session variable—there is
no need to connect to, select, and query the database.
Comments
Post a Comment