0% found this document useful (0 votes)
76 views

Chapter 3 - File Handling

The document discusses storing information in flat files versus databases. It then covers various PHP functions for working with files, including opening, reading, writing, and getting metadata from files. The document also discusses including one PHP file in another using include() and require() to reuse code.

Uploaded by

Meku T
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)
76 views

Chapter 3 - File Handling

The document discusses storing information in flat files versus databases. It then covers various PHP functions for working with files, including opening, reading, writing, and getting metadata from files. The document also discusses including one PHP file in another using include() and require() to reuse code.

Uploaded by

Meku T
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/ 11

Chapter Three

Files and Directories


File Vs Database

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.

PHP - File Create and Open


In PHP, a file is created using a command that is also used to open files. It may seem a little
confusing, but we'll try to clarify this conundrum. In PHP the fopen function is used to open
files. However, it can also create a file if it does not find the file specified in the function call.
So if you use fopen on a file that does not exist, it will create it, given that you open the file for
writing or appending (more on this later). The fopen() function is used to open files in PHP.The
first parameter of this function contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened:
<html><body>
<?php
$file=fopen("welcome.txt","w");
?>
</body></html>
• The file may be opened in one of the following modes:
Note: If the fopen() function is unable to open the specified file, it returns 0 (false).

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

The fclose() function is used to close an open 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!

Reading a File Line by Line


• The fgets() function is used to read a single line from a file.
• Note: After a call to this function the file pointer has moved to the next line.
Example
The example below reads a file line by line, until the end of file is reached:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>
Reading a File Character by Character
• The fgetc() function is used to read a single character from a file.
• Note: After a call to this function the file pointer moves to the next character.
Example
The example below reads a file character by character, until the end of file is reached:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file) . "<br>";
  }
fclose($file);
?>

Writing to a File

• Writing to a file in PHP is relatively simple.


• You can use either of the functions fwrite() or fputs()
• fputs() is an alias to fwrite().
• We call fwrite() in the following:
fwrite($fp, $outputstring);
• This tells PHP to write the string stored in $outputstring to the file pointed to by $fp.
• Example: write data to file
<?php
$fh = fopen(“test.txt”,”a”);
$data = “This content is written to file \n”;
$data = $data . “This line is also written”;
fwrite($fh, $data);
fclose($fh);
?>

Getting information about files


• Often you want to know information about a file. PHP has functions that allow you to
find out file information about the files from within a script.You can find out whether a
file exists with the file_exists statement, as follows:
$result = file_exists(filename);
• After this statement, $result contains either TRUE or FALSE. The function is often used
in a conditional statement, such as the following:
if(!file_exists(“stuff.txt”))
{
echo “File not found!\n”;
}

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

PHP Include File

• 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

PHP include() Function


• The include() function takes all the content in a specified file and includes it in the
current file
• If an error occurs, the include() function generates a warning, but the script will continue
execution
Example 1
• Assume that you have a standard footer file, called "footer.php". To include the footer file
in a page, use the include() function:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>

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

PHP require() Function


• The require() function is identical to include(), except that it handles errors differently.
• If an error occurs, the include() function generates a warning, but the script will continue
execution.
• The require() generates a fatal error, and the script will stop.

Error Example include() Function


<html>
<body>
<?php
include("wrongFile.php");
echo "Hello World!";
?>
</body>
</html>
Notice that the echo statement is executed! This is because a Warning does not stop the script
execution.

Error Example require() Function


Now, let's run the same example with the require() function.

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

Create an Upload-File Form


• To allow users to upload files from a form can be very useful.
• Look at the following HTML form for uploading files:
<html>
<body>
<form action="upload_file.php" method="post“ enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Notice the following about the HTML form above:

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

Create The Upload Script


The "upload_file.php" file contains the code for uploading a 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:

Saving the Uploaded File


• The examples above create a temporary copy of the uploaded files in the PHP temp
folder on the server.
• The temporary copied files disappears when the script ends. To store the uploaded file we
need to copy it to a different location:
• The general format of the statement that moves the file is as follows:
move_uploaded_file(path/tempfilename, path/permfilename);
• You can use the following statement to move the file to your desired location, in this
case, c:\data\new_file.txt:
move_uploaded_file($_FILES[‘user_file’][‘tmp_name’],
‘c:/data/new_file.txt’);
The destination directory (in this case, c:\data) must exist before the file can be moved to it.
This statement doesn’t create the destination directory.

<?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 />";

•  if (file_exists("upload/" . $_FILES["file"]["name"]))


      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy