0% found this document useful (0 votes)
24 views23 pages

Web Development BCS IV Sem Unit IV

Php

Uploaded by

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

Web Development BCS IV Sem Unit IV

Php

Uploaded by

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

Unit IV- Web Forms, Cookies, and File Handling

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

<select name="products" multiple>

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>

Working with HTML and PHP code on a single page


Circumstances, you might want to include form-parsing code on the same page as a hard-coded
HTML form. Such a combination can be useful if you need to present the same form to the user
more than once. You would have more flexibility if you were to write the entire page
dynamically, of course, but you would miss out on one of the great strengths of PHP. The more
standard HTML you can leave in your pages, the easier they are for designers and page builders
to amend without reference to you. You should avoid scattering substantial chunks of PHP code
throughout your documents, however. Doing so makes them hard to read and maintain. Where
possible, you should create functions that can be called from within your HTML code and can be
reused in other projects.
For the following examples, imagine that we're creating a site that teaches basic math to
preschool children, and have been asked to create a script that takes a number from form input
and tells the user whether it's larger or smaller than a predefined integer.
Listing 9.6 creates the HTML. For this example, we need only a single text field, but even so,
we'll include a little PHP.
Listing 9.6 An HTML Form That Calls Itself

<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.

Saving State with a Hidden Field


Math1.php

<body>

<h1> First Number</h1>

<form action="math2.php" method="post">

<label for= "fn"> First Number </label>

<input type="text" name="fn" value="" id="fn" >


<p> <input type="submit" value="continue &rarr;"></p>

</form>>

</body>

Math2.php

<body>

<h1> Second Number</h1>

<form action="math3.php" method="post">

<input type="hidden" name="fn" value=" <?php echo $_POST['fn'] ?> " id="fn" >

<label for= "sn"> Second Number </label>

<input type="text" name="sn" value="" id="sn" >

<p> <input type="submit" value="continue &rarr;"></p>

</form>>

</body>

Math3.php

<?php

$ans = $_POST['fn'] + $_POST['sn'] ;

?>

<body>

<h1> Answer is .....</h1>

<?php

echo "The Answer is $ans";

?>

</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.

Create Cookies With PHP


A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie


The following example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).

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).

Modify a Cookie Value


To modify a cookie, just set (again) the cookie using the setcookie() function:

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.

Unlike a cookie, the information is not stored on the users computer.

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.

Start a PHP Session / Session Functions


A session is started with the session_start() function.

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:

Session variables are set.


Note: The session_start() function must be the very first thing in your document. Before any HTML
tags.

Get PHP Session Variable Values


Next, we create another page called "demo_session2.php". From this page, we will access the session
information we set on the first page ("demo_session1.php").

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 .

Modify a PHP Session Variable


To change a session variable, just overwrite it:

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:

Array ( [favcolor] => yellow )

Destroy a PHP Session


To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>

Output:
All session variables are now removed, and the session is destroyed.

Working with Files and Directories with PHP


These examples demonstrate how to work with files and directories in PHP including:

 Reading, writing, and appending files


 Getting file size
 Checking if a file exists
 Creating, checking, changing, and removing directories
 Listing directory contents
 Working with JSON
 Searching directories for files
 Reading and writing compressed files

File open modes


When opening a file, there are several different modes you can use. The most common ones are r
and w for read and write. There are several more available though that will control whether you
create a new file, open an existing file, and whether you start writing at the beginning or the end.
These modes are used with fopen() in the rest of the examples.

r - read only

w - write only, force new file

a - write only with pointer at end

x - write only, create new file or error on existing

r+ - read/write, file pointer at beginning

w+ - read/write, force new file

a+ - read/write, file pointer at end

x+ - read/write, create new file or error on existing

Write to a file
When writing files you have two primary options that we will look at:

 Writing bytes as needed with fwrite()


 Writing the entire file contents at once with file_put_contents()

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

$file = fopen('hello.txt', "w") or die("Unable to open file!");

fwrite($file, "Hello, world!\n");

fclose($file);

WRITE ENTIRE FILE AT ONCE


This is more convenient and perfect for smaller files that won't exhaust the system RAM.

<?php

file_put_contents('hello.txt', "Hello, world, again!\n");


Read from a file
When reading a file you have the same two primary options that we will look at:

 Reading bytes as needed with fread()


 Reading the entire file in to a variable with file_get_contents()

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);

$file = fopen($filename, 'r');

$contents = fread($file, $number_of_bytes_to_read);

echo $contents;

// You can check for EOF with `feof()`

echo feof($file);

READ ENTIRE FILE AT ONCE


This is more memory intensive but convenient. It is best for smaller files that will not exhauset
the system RAM.

<?php

$contents = file_get_contents('test.txt');

echo $contents;

READ ALL LINES OF A TEXT FILE


To quickly get an array containing each line of a file, use the file() function.

<?php

$lines = file('test.txt'); // Each line will still have it's line ending character

print_r($lines);

Common file tasks


Here are some examples of other common tasks I perform with files like:
 Getting file size
 Checking if a file exists
 Check if a file is a directory
 Get a lock on a file
 Read and write JSON

GET FILESIZE

You can quickly get the size of a file in bytes using the filesize() function.

<?php

echo filesize('hello.txt');

CHECK IF FILE EXISTS


You can easily check if a file exists with the file_exists() function.

<?php

echo file_exists('hello.txt');

GET AN EXCLUSIVE LOCK ON A FILE


This is useful when you want to ensure only one write operation is happening at a time. For
example, if you have a file that stores an integer called hit_counter.txt you will want to make
sure there is no race condition and that multiple writes are not happening at once.

<?php

$file = fopen('safe.txt', 'a');

// https://www.php.net/manual/en/function.flock.php

flock($file, LOCK_EX); // Get exclusive lock on file

// Perform read/write actions while holding the lock

fwrite($file, "Test\n");

flock($file, LOCK_UN); // Release file lock

fclose($file);

PHP Delete File


In PHP, we can delete any file using unlink() function. The unlink() function accepts one
argument only: file name. It is similar to UNIX C unlink() function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.

Syntax

bool unlink ( string $filename [, resource $context ] )

$filename represents the name of the file to be deleted.

PHP Delete File Example


<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>

Output

File deleted successfully

WORKING WITH JSON


A common task is to take data from a PHP array and convert it to a JSON string for storage on
disk. Then later reading the file with the JSON string and created a PHP array to work with. To
learn more about PHP and JSON check out my tutorial, Working with JSON in PHP.

Here is a basic example of reading and writing a JSON file.

<?php

// Store a PHP object as a JSON string

file_put_contents('test.json', json_encode([2, 4, 6]));

// Read JSON string in to a PHP object

$my_array = json_decode(file_get_contents('test.json'));

print_r($my_array);

READING AND WRITING FROM STDIN, STDOUT, AND STDERR


If you want to explicitly work with the standard input, output, and error streams, you can use
them with special named constants STDOUT, STDIN, and STDERR.

<?php

// test.php

fwrite(STDOUT, "Hello, world!\n");

fwrite(STDERR, "Hello, error! Enter some text:\n");

$input = fread(STDIN, 1024);

fwrite(STOUT, "Input received: " . $input . "\n");

Then run the file, and enter some text and press enter. Alternatively you can pipe some content in
to STDIN like this:

echo "Testing" | php test.php

CHECK IF FILE IS A DIRECTORY


To check if a directory entry is a file or a directory, you can use is_dir() function.

<?php

echo is_dir('/path/to/check');

GET CURRENT WORKING DIRECTORY


You can check what directory you are in with the getcwd() function.

<?php

echo getcwd();

GET THE DIRECTORY THAT THE PHP FILE IS IN


This is useful for creating paths relative to the PHP file no matter what the current working
directory is.

<?php

echo __DIR__;

GET THE PATH OF THE PHP FILE BEING EXECUTED


This is useful for checking what the full path of the PHP file is

<?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');

GET DIRECTORY CONTENTS


If you want to list the contents of a directory you have two main options:

 scandir() - scandir() will return all contents of a directory

 glob() - glob() lets you search for contents in a directory using a pattern like *.* or *.png

Which one you use will depend on your needs.

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.

Some example search patterns you can use are:

 *
 ./*

 /path/to/search/*

 *.*

 *.jpg

 log*

<?php

$all_contents = glob("*");

print_r($all_contents);

$log_entries = glob("*log*");

print_r($log_entries);

PHP Include Files


The include (or require) statement takes all the text/code/markup that exists in the specified file
and copies it into the file that uses the include statement.

Including files is very useful when you want to include the same PHP, HTML, or text on
multiple pages of a website.

PHP include and require Statements


It is possible to insert the content of one PHP file into another PHP file (before the server
executes it), with the include or require statement.

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';

PHP include Examples


Example 1

Assume we have a standard footer file called "footer.php", that looks like this:

<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>

To include the footer file in a page, use the include statement:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</body>
</html>

Output:

Welcome to my home page!


Some text.

Some more text.

Copyright © 1999-2024 W3Schools.com

Example 2

Assume we have a standard menu file called "menu.php":

<?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>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>

</body>
</html>

Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP 7 Tutorial

Welcome to my home page!


Some text.

Some more text.

You might also like