Web Development BCS IV Sem Unit IV
Web Development BCS IV Sem Unit IV
Creating a Simple Input Form and Accessing Form Input with User-
Defined Arrays
The examples so far enable us to gather information from HTML elements that submit a single
value per element name. This leaves us with a problem when working with SELECT elements.
These elements make it possible for the user to choose multiple items. If we name
the SELECT element with a plain name, like so
the script that receives this data has access to only a single value corresponding to this name. We
can change this behavior by renaming an element of this kind so that its name ends with an
empty set of square brackets.
An HTML Form Including a SELECT Element
<html>
<body>
<form action="listing9.5.php" method="POST">
Name: <br>
<input type="text" name="user">
<br>
Address: <br>
<textarea name="address" rows="5" cols="40"></textarea>
<br>
Pick Products: <br>
<select name="products[]" multiple>
<option>Sonic Screwdriver</option>
<option>Tricorder</option>
<option>ORAC AI</option>
<option>HAL 2000</option>
</select>
<br><br>
<input type="submit" value="hit it!">
</form>
</body>
</html>
Put these lines into a text file called listing9.4.php, and place that file in your Web server
document root. Next, in the script that processes the form input, we find that input from
the "products []" form element created on line 14 is available in an array
called $_POST[products]. Because products [] is a SELECT element, we offer the user multiple
choices using the option elements on lines 15 through 18. We demonstrate that the user's choices
are made available in an array in Listing 9.5.
Reading Input from the Previous Form
<html>
<body>
<?php
print "Welcome <b>$_POST[user]</b><p>\n\n";
print "Your address is:<p>\n\n<b>$_POST[address]</b><p>\n\n";
print "Your product choices are:<p>\n\n";
if (!empty($_POST[products])) {
print "<ul>\n\n";
foreach ($_POST[products] as $value) {
print "<li>$value\n";
}
print "</ul>";
}
?>
</body>
</html>
Put these lines into a text file called listing 9.5.php, and place that file in your Web server
document root. Now access the form in Listing 9.4 with your Web browser and fill out the fields.
Figure 9.3 shows an example.
On line 7 of the script in Listing 9.5, we access the $_POST[user] variable, which is derived
from the user form element. On line 10, we test for the $_POST[products] variable.
If $_POST[products] is present, we loop through it on line 12, and output each choice to the
browser on line 13.
Submit the form and you might see something like that shown in Figure 9.4.
Although the looping technique is particularly useful with the SELECT element, it works with
every form element. For example, by giving a number of check boxes the same name, you can
enable a user to choose many values within a single field name. As long as the name you choose
ends with empty square brackets, PHP compiles the user input for this field into an array. We can
replace the SELECT elements from lines 15-18 in Listing 9.4 with a series of check boxes to
achieve the same effect:
<input type="checkbox" name="products[]" value="Sonic
Screwdriver">Sonic Screwdriver<br>
<input type="checkbox" name="products[]" value="Tricorder">Tricorder<br>
<input type="checkbox" name="products[]" value="ORAC AI">ORAC AI<br>
<input type="checkbox" name="products[]" value="HAL 2000">HAL 2000<br>
<html>
<head>
<title>Listing 9.6 An HTML form that calls itself</title>
</head>
<body>
<form action="<? php print $_SERVER[PHP_SELF] ?>" method="POST">
Type your guess here: <input type="text" name="guess">
</form>
</body>
</html>
The action of this script is $_SERVER[PHP_SELF]. This variable is the equivalent of the name
of the current script. In other words, the action tells the script to reload itself.
The script in Listing 9.6 doesn't produce any output. In Listing 9.7, we begin to build up the PHP
element of the page. First, we must define the number that the user guesses. In a fully working
version, we'd probably randomly generate this number, but for now, we keep it simple. We
assign 42 to the $num_to_guess variable on line 2. Next, we must determine whether the form
has been submitted; otherwise, we'd attempt to assess variables that aren't yet made available.
We can test for submission by testing for the existence of the variable $_POST[guess], which is
made available if your script has been sent a "guess" parameter. If $_POST[guess] isn't present,
we can safely assume that the user arrived at the page without submitting a form. If the
value is present, we can test the value it contains. The test for the presence of
the $_POST[guess] variable takes place on line 4.
Listing 9.7 A PHP Number-Guessing Script
<?php
$num_to_guess = 42;
$message = "";
if (!isset($_POST[guess])) {
$message = "Welcome to the guessing machine!";
} 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 { // must be equivalent
$message = "Well done!";
`}
?>
<html>
<head>
<title>Listing 9.7 A PHP number guessing script</title>
</head>
<body>
<h1>
<?php print $message ?>
</h1>
<form action="<?php print $_SERVER[PHP_SELF] ?>" method="POST">
Type your guess here: <input type="text" name="guess">
</form>
</body>
</html>
Put these lines into a text file called listing9.7.php, and place this file in your Web server
document root. Now access the script with your Web browser, and you should see something
like Figure 9.5.
The bulk of this script consists of an if statement that determines which string to assign to the
variable $message. If the $_POST[guess] variable hasn't been set, we assume that the user has
arrived for the first time and assign a welcome string to the $message variable on line 5.
Otherwise, we test the $_POST[guess] variable against the number we stored in $num_to_guess,
and assign advice to $message accordingly. We test whether $_POST[guess] is larger
than $num_to_guess on line 6, and whether it's smaller than $num_to_guess on line 8.
If $_POST[guess] is neither larger nor smaller than $num_to_guess, we can assume that it's
equivalent and assign a congratulations message to the variable (line 11). Now all we must do is
print the $message variable within the body of the HTML.
There are still a few more additions, but you can probably see how easy it would be to hand this
page over to a designer. He can make it beautiful without having to disturb the programming in
any way.
Using Hidden Fields to Save State in PHP & redirecting the user
Use a hidden field to keep track of this value.
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.
<body>
</form>>
</body>
Math2.php
<body>
<input type="hidden" name="fn" value=" <?php echo $_POST['fn'] ?> " id="fn" >
</form>>
</body>
Math3.php
<?php
?>
<body>
<?php
?>
</body>
Output:-
Introduction to 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.
With PHP, you can both create and retrieve cookie values.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
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:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Check if Cookies are Enabled
The following example creates a small script that checks whether cookies are enabled. First, try to
create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
When you work with an application, you open it, do some changes, and then you 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.
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.
Tip: If you need a permanent storage, you may want to store the data in a database.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session
and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Output:
Notice that session variables are not passed individually to each new page, instead they are retrieved
from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Output:
Favorite color is .
Favorite animal is .
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
output:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
Output:
All session variables are now removed, and the session is destroyed.
r - read only
Write to a file
When writing files you have two primary options that we will look at:
WRITE BYTES
This example shows how to write to a file with some basic text. First, open with fopen() then
You can keep writing to the file with fwrite() until you are done, and then call fclose().
<?php
fclose($file);
<?php
READ BYTES
This example will read N number of bytes in to a variable with fread(). In this case, it will read
all the bytes based on the length of the file. You could just read one or two bytes at a time. It will
return FALSE if it fails. You can check if the end of file has been reached with feof().
<?php
$filename = 'test.txt';
$number_of_bytes_to_read = filesize($filename);
echo $contents;
echo feof($file);
<?php
$contents = file_get_contents('test.txt');
echo $contents;
<?php
$lines = file('test.txt'); // Each line will still have it's line ending character
print_r($lines);
GET FILESIZE
You can quickly get the size of a file in bytes using the filesize() function.
<?php
echo filesize('hello.txt');
<?php
echo file_exists('hello.txt');
<?php
// https://www.php.net/manual/en/function.flock.php
fwrite($file, "Test\n");
fclose($file);
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.
Syntax
Output
<?php
$my_array = json_decode(file_get_contents('test.json'));
print_r($my_array);
<?php
// test.php
Then run the file, and enter some text and press enter. Alternatively you can pipe some content in
to STDIN like this:
<?php
echo is_dir('/path/to/check');
<?php
echo getcwd();
<?php
echo __DIR__;
<?php
echo __FILE__;
CHANGE DIRECTORY
You can easily change directories with the chdir() function.
<?php
chdir('/path/to/change/to/');
echo getcwd();
MAKE DIRECTORY
You can make a directory with mkdir().
<?php
mkdir('/path/to/make');
REMOVE DIRECTORY
Similarly, delete a directory with rmdir().
<?php
rmdir('/path/to/delete');
glob() - glob() lets you search for contents in a directory using a pattern like *.* or *.png
scandir()
The scandir() function will list everything in a directory. It will include both files and directories.
Contents includes . and .. entries.
<?php
$contents = scandir('.');
print_r($contents);
glob()
The glob() function lets you search a directory for contents using a pattern. It will return files and
directories found.
*
./*
/path/to/search/*
*.*
*.jpg
log*
<?php
$all_contents = glob("*");
print_r($all_contents);
$log_entries = glob("*log*");
print_r($log_entries);
Including files is very useful when you want to include the same PHP, HTML, or text on
multiple pages of a website.
The include and require statements are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is
missing, use the include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP
application coding, always use the require statement to include a key file to the flow of
execution. This will help avoid compromising your application's security and integrity, just in-
case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard header, footer, or
menu file for all your web pages. Then, when the header needs to be updated, you can only
update the header include file.
Syntax
include 'filename';
or
require 'filename';
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
Example
<html>
<body>
</body>
</html>
Output:
Example 2
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done (we are using a
<div> element so that the menu easily can be styled with CSS later):
Example
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>