Code2Design.com

User login

The Layout

Programming

Graphic Design

Resources

Navigation

C2D Projects

Unsystematic Affiliates

Tutorials Expert Flash Valley AOM Designs GameXe 

Change Language

Who's online

There are currently 0 users and 6 guests online.

Lesson 16 - Reading External Files into PHP

Now it's time for us to learn how to use PHP's file API to create, edit, and destroy files through PHP.

"One of the most basic things you can do with any programming language is create and manipulate data structures. These structures may be transient - in-memory variables like arrays or objects - or more permanent - disk-based entities like files or database tables; however, the ability to create, modify and erase them in a convenient and consistent manner is of paramount importance to any programmer.

Like all widely used programming languages, PHP has the very useful ability to read data from, and write data to, files on the system. But the language doesn't just stop there - PHP comes with a full-featured file-and-directory-manipulation API that allows you (among other things) to view and modify file attributes, read and list directory contents, alter file permissions, retrieve file contents into a variety of native data structures, and search for files based on specific patterns. This file manipulation API is both powerful and flexible - two characteristics that will endear it to any developer who's ever had to work with file manipulation commands." -Melonfire

fread
Start by making a file in the same folder as your php scripts. Name the file "file.txt" and write something in it like:

If you can read this my script works!
Or maybe it doesn't...
That's it!
The computer is just guessing what is in the file...

(Note: It is important that you type at least 4 lines worth of text.)
Then close the file and make a new file named "fileopen.php" and type this into it:

<?php
// Store the file name in a string.
$filename "file.txt";

// Open the file.
$filehandle fopen($filename"r");

// Read the files contents.
$contents fread($filehandlefilesize($filename));

// Close file.
fclose($filehandle);

// Echo the files contents
echo $contents;
?>

When you run the script you will see a blank screen with the text "If you can read this my script works!" on it. If you get an error double check your code and make sure that "file.txt" and "fileopen.php" are in the same place.

Now to explain what the script does:

<?php
// Store the file name in a string.
$filename "file.txt";
?>

Here we start by putting the name of the file we want in a string.

<?php
// Open the file.
$filehandle fopen($filename"r");
?>

Next we create a "file handle" which is kind of hard to explain, but basically it is how the computer now can remember the file. It is a "handle" that can be used to tell the computer what your referring too. I'm sure you've herd the saying "What's your Handle?" in street/gangster movies. I'm sure your probably wondering what the "r" means, it is the type of mode to open the file in - "READ" mode. For all modes see the bottom of the page.

<?php
// Read the files contents.
$contents fread($filehandlefilesize($filename));
?>

Here we read (fread) the contents of the file into a string. Notice that there are two different parts to fread(). The first is the handle we will use to tell the script what file we want to open. The next is the number of bytes to be read. You could put a number like this:

<?php
// Read the files contents.
$contents fread($filehandle4068);
?>

Where the script will stop reading the file when it gets to 4068 bytes or the end of the script. (Which ever comes first)

However I find it easier to just tell the script to get as many bytes as there are:

<?php
filesize
($filename)
?>

<?php
// Close file.
fclose($filehandle);

// Echo the files contents
echo $contents;
?>

Last we close the file and destroy the file handle. Then print the files contents to the screen. You don't have to close the file handle, but your scripts will end up with a lot of open files if you don't...

readfile

The simplest way to read a file into php and output it to the screen is to use the readfile() function.

<?php
// Store the file name in a string.
$filename "file.txt";

// Prints the files contents.
readfile($filename);
?>

fgets

Here is another way to open a file and get the contents. "fgets" gets one line out of the file specified by the file handle.

<?php
// Store the file name in a string.
$filename "file.txt";

// Open the file.
$filehandle fopen($filename"r");

// Read the file line by line into a string.
while (!feof($filehandle))
{
   
$contents .= fgets($filehandle);
}

// Close file.
fclose($filehandle);

// Echo the files contents
echo $contents;
?>

The first part specifies the file to open and creates a "handle" for it:

<?php
// Store the file name in a string.
$filename "file.txt";

// Open the file.
$filehandle fopen($filename"r");
?>

Next we need to recal that lesson about loops to understand the "while" loop:

<?php
// Read the file line by line into a string.
while (!feof($$filehandle))
{
   
$contents .= fgets($fh);
}
?>

Basicaly, in human language it says:
While it is not the END OF THE FILE (feof: FILE END OF) {
Get a line out of the file and add it to the string $contents.
($contents .= fgets($fh))
}

Note: the little dot in front of the "=" sign means "add to". If the code was:
<?php
    $contents 
fgets($fh);
?>

Then every time the while loop ran it would over write the old value of $contents with a new value. But we don't want it to do that! We want it to add the new value to $contents.

File

Last I want to show you how to read a file into an array! If you haven't read the lesson on arrays you need to do so now! (I also recommend that you open "file.txt" and change the text because it is getting old....)

<?php
// Store the file name in a string.
$filename "file.txt";

// Read file into array
$contents file($filename);

// Loop through the array and print each line to the screen.
foreach ($contents as $line)
{
   echo 
$line;
}
?>

Ok, this one is the hardest, but don't worry we'll get it down!
In English the foreach loop looks like this:

For every element/line in the array "$contents": put that element into a variable called "$line" {
Then print the value of "$line" to the screen.
}

Hope this lesson helped you to understand how to read files into PHP Scripts Next lesson I will show you how to do more advanced things with files!

MODES

Here are all of the modes for the fopen() function:

mode Description
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files.
'x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files.

Taken from the PHP Manual


Submitted by David on November 10, 2006 - 7:55pm.
printer friendly version

Open file from an ftp

Does the file have to be in the same directory as the php script or can $filename be a path to the file along with the file?


You can open a file from a path

It can be a path like "html/website/index.html" for scripts in directories below the curent php script running this code.

<?php
// Store the file name in a string.
$filename "dir/www/file.txt";

// Read file into array
$contents file($filename);
?>

Now if you need to get the contents of a file that is in a different directory on the same level (or higher) than the directory with the php script you would use the Unix statement "../" before your file path. Let me demonstrate. lets say the php file script is in "dir1" but we want to read a text file in "Subdirofdir2":

>website

>>dir1 <-PHP Script
>>>Subdirofdir1

>>dir2
>>>Subdirofdir2 <-Text File

We can't use the path "dir2/subdirofdir2/text.txt" because there is no path like that in the current php script's directory. (the php script is in "dir1" remember). However if we could get to the "website" directory (which is the root) we could then use the "dir2/subdirofdir2/text.txt" path and it would work. So if we add the unix "../" before the path php will look for the path in the directory 1 above the current directory path (which is "website").

So our path from the php script to the text file should be:

<?php
// Go up one level - then look for the "dir2" directory.
$filename "../dir2/subdirofdir2/text.txt";

// Read file into array
$contents file($filename);
?>


Hi, Is there a way to get it

Hi,

Is there a way to get it to read from a specific string in the file, to another specific string, for example, if I wanted to get the code out of an html file, from to and assign it to $first?

Thanks!


Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br> <br /> <h3>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use BBCode tags in the text, URLs will be automatically converted to links
More information about formatting options



Like what you see?

Why not add more? C2D is looking for other Christian Web Masters who would like to help write articles for this site. If you have expericance in FLASH, CSS/HTML, PHP/MySQL, PhotoShop/GIMP, Blender, Javascript, or just General Design - our users would love to hear what you have to say. Contact Us

delicious   digg   reddit   magnoliacom   newsvine   furl   google   yahoo   technorati