Chapter 3 - File Handling
Chapter 3 - File Handling
Many applications require the long-term storage of information. Information can be stored on the
server in flat files or in databases. Flat files are text files stored in the computer file system. You
can access and edit these files by using any text editors such as notepad. The information in the
flat file is stored as strings, and the PHP script that retrieves the data needs to know how the data
is stored. For example, to retrieve a customer name from a file, the PHP script needs to know
that the customer name is stored in the first 20 characters of every line. Using a database for data
storage requires you to install and learn to use database software, such as MySQL or Oracle.
The data is stored in the database and can only be accessed by the database software. Databases
can store very complex information that you can retrieve easily. You don’t need to know how the
data is stored, just how to interact with the database software. The database software handles the
storage and delivers the data, without the script needing to know exactly where or how the
customer name is stored.
• Flat files have some advantages over databases:
• Available and versatile: You can create and save data in any operating system’s
file system. You don’t need to install any extra software.
• Additionally, text data stored in flat files can be read by a variety of software
programs, such as word processors or spreadsheets.
• Easy to use: You don’t need to do any extra preparation, such as install database
software, design a database, create a database, and so on.
• Just create the file and store the data with statements in your PHP script.
• Smaller: Flat files store data by using less disk space than databases.
• Databases have advantages as well:
• Security: A database provides a security layer of its own, in addition to the security
provided by the operating system.
• A database protects the data from outside intrusion better than a flat file.
• Accessibility of data: You can store data in a database by using a very complex data
structure, specifying data types and relationships among the data.
• The organization of the data makes it easy to search the data and retrieve what you
need.
• Ability to handle multiple users: When many users store or access data in a single file,
such as a file containing names and addresses, a database ensures that users take their
turn with the file to avoid overwriting each other’s data.
PHP Files
• Manipulating files is a basic necessity for serious programmers and
• PHP gives you a great deal of tools for creating, uploading, and editing files.
Example
The following example generates a message if the fopen() function is unable to open the
specified file:
<html>
<body>
<?php
$file=fopen("welcome.txt","w") or exit("Unable to open file!");
?>
</body>
</html>
Closing a File
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
Check End-of-file
• The feof() function checks if the "end-of-file" (EOF) has been reached.
• The feof() function is useful for looping through data of unknown length.
• Note: You cannot read from files opened in w, a, and x mode!
Writing to a File
Reusing Code
One of the goals of software engineers is to reuse code instead of writing new code. Reusing
existing code reduces costs, increases reliability, and improves consistency. Ideally, a new
project is created by combining existing reusable components, with a minimum of development
from scratch. PHP provides two very simple, yet very useful, statements to allow you to reuse
any type of code. Using include or require statement, you can load a file into your PHP script.
The file can contain anything you would normally type in a script including PHP statements,
text, HTML tags, etc
• You can insert the content of one PHP file into another PHP file before the server
executes it, with the include() or require() function
• The two functions are identical in every way, except how they handle errors:
include() generates a warning, but the script will continue execution
require() generates a fatal error, and the script will stop
<html><body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body></html>
• Assume we have a standard menu file, called "menu.php", that should be used on all
pages:
<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>
All pages in the Web site should include this menu file. Here is how it can be done:
<html>
<body>
<div class="leftmenu">
<?php include("menu.php"); ?>
</div>
<h1>Welcome to my home page.</h1>
<p>Some text.</p>
</body>
</html>
<html>
<body>
<?php
require("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
• The echo statement is not executed, because the script execution stopped after the fatal
error. It is recommended to use the require() function instead of include(), because scripts
should not continue after an error.
PHP File Upload
• You may want users to upload files to your Web site.
• For example, you may want users to be able to upload resumes to your job-search Web
site or pictures to your photo album Web site.
• Security can be an issue when uploading files.
• Allowing strangers to load files onto your computer is risky; malicious files are possible.
• So, check the files for as many factors as possible after they are uploaded, using
conditional statements to check file characteristics, such as checking for the expected file
type and for the size.
• In some cases, for even more security, it may be a good idea to change the name of the
file to something else so users don’t know where their files are or what they’re called.
The enctype attribute of the <form> tag specifies which content-type to use when submitting the
form. “multipart/form-data" is used when a form requires binary data, like the contents of a file,
to be uploaded. The type="file" attribute of the <input> tag specifies that the input should be
processed as a file. For example, when viewed in a browser, there will be a browse-button next
to the input field.
Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform
file uploads.
Accessing Information about an Uploaded File
• Along with the file, information about the file is sent with the form.
• This information is stored in the PHP built-in array called $_FILES
• An array of information is available for each file that was uploaded.
• You can obtain the information from the array by using the name of the field.
$_FILES[‘fieldname’][‘name’] – contains filename
$_FILES[‘fieldname’][‘type’] – contains type of file
$_FILES[‘fieldname’][‘tmp_name’] – contains temporary location of file
$_FILES[‘fieldname’][‘size’] – contains size of file
• For example, suppose you use the following field to upload a file:
<input type=”file” name=”user_file”>
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
• By using the global PHP $_FILES array you can upload files from a client computer to
the remote server.
• The first parameter is the form's input name and the second index can be either "name",
"type", "size", "tmp_name" or "error". Like this:
$_FILES["file"]["name"] - the name of the uploaded file
$_FILES["file"]["type"] - the type of the uploaded file
$_FILES["file"]["size"] - the size in bytes of the uploaded file
$_FILES["file"]["tmp_name"] - the name of the temporary copy of the file
stored on the server
$_FILES["file"]["error"] - the error code resulting from the file upload
• This is a very simple way of uploading files. For security reasons, you should add
restrictions on what the user is allowed to upload.
Restrictions on Upload
• In this script we add some restrictions to the file upload. The user may only upload .gif or
.jpeg files and the file size must be under 20 kb:
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";