Home arrow PHP arrow Page 4 - File And Directory Manipulation In PHP (part 1)

Weapon Of Choice - PHP

PHP comes with a powerful and flexible file manipulation API that allows developers (among other things) to read and write files, view and modify file attributes, read and list directory contents, alter file permissions, and retrieve file contents into a variety of native data structures. Find out more, inside.

  1. File And Directory Manipulation In PHP (part 1)
  2. Handle With Care
  3. Different Strokes
  4. Weapon Of Choice
  5. Weather Balloon
  6. A Matter Of Existence
  7. Permission Granted
  8. In Stat We Trust
  9. A Short Break
By: icarus, (c) Melonfire
Rating: starstarstarstarstar / 74
August 07, 2003

print this article



If you've used C before, you're probably already familiar with the "include" directive that appears near the beginning of every C program. Since we're talking about reading files, it's appropriate to bring in PHP's equivalent - the include() and require() functions, which come in handy when you need to read an external file into your PHP script.

Consider the following simple example, which illustrates:

<title>Weapons Worth Dying For</title>
h1,h3,li { font-family:Verdana; }

// this time, Bond's going to need the cigarette-lighter gun... require("./gun.php4");

// the new car-copter...

// and of course, the gold watch with the hidden GPS locator require("./watch.php4");


<h3>So, James, here's your check list for the mission.</h3>
<ol type="a">
<li>The gun: <?php echo "$gun"; ?>
<li>The car: <?php echo "$car"; ?>
<li>The watch: <?php echo "$watch"; ?>
<h3>Oh yes...and remember never to let them see you cry. Good luck, 007!</h3> </body> </html>

Now, if you try to access this page as it, you'll get a bunch of error messages warning you about missing files. So you need to create the files "gun.php4", "car.php4" and "watch.php4":

// gun.php4
$gun = "AK-47";

// car.php4
$car = "BMW G8";

// watch.php4
$watch = "Rolex SAW-007";

And this time, when you access the primary page, PHP should automatically include the specified files, read the variables $gun, $watch and $car from them, and display them on the page.

Files named in the include() and require() functions are searched for in a set of default locations. These locations are specified via PHP's "include_path" configuration directive, which may be set globally in the main "php.ini" configuration file, or on a per-script basis using the
ini_set() function call.

A quick note on the difference between the include() and require() functions - the require() function returns a fatal error if the named file cannot be found and halts script processing, while the include() function returns a warning but allows script processing to continue.

An important point to be noted is that when a file is require()-d or include()-d, the PHP parser leaves "PHP mode" and goes back to regular "HTML mode". Therefore, all PHP code within the included external files needs to be enclosed within regular PHP <?...?> tags.

A very useful and practical application of the include() function is to use it to include a standard footer or copyright notice across all the pages of your Web site, like this:



...your HTML page...


<?php include("footer.html"); ?>


where "footer.html" contains

<font size=-1 face=Arial>This material copyright Melonfire, 2003. All rights reserved.</font>

Now, this footer will appear on each and every page that contains the
include() statement above - and, if you need to change the message, you only need to edit the single file named "footer.html"!

Note also that PHP also offers the require_once() and include_once() functions, which ensure that a file which has already been read is not read again. This can come in handy if you have a situation in which you want to eliminate multiple reads of the same include file, either for performance reasons or to avoid corruption of the variable space.

{mospagebreak title=A Little Brainwashing}

Obviously, reading a file is no great shakes - but how about writing to a file? Well, this next script does just that:


// set file to write
$filename = "matrix.txt";

// open file
$fh = fopen($filename, "w") or die("Could not open file!");

// write to file
fwrite($fh, "Welcome to The Matrix, Neo") or die("Could not write to file");

// close file


Now, once you run this script, it should create a file named "matrix.txt", which contains the text above.

As you can see, in order to open a file for writing, you simply need to use the same fopen() function, but with a different mode ("w" for write).


// open file
$fh = fopen($filename, "w") or die("Could not open file!");


A number of different modes are available for the fopen() function - you've already seen two, here are a few more:

r Opens a file in read mode

w Opens a file in write mode; existing file contents are truncated

a Opens a file in append mode; existing file contents are preserved

You can add a "+" to any of the modes above to open the file for simultaneous read and write. In case the named file does not exist in any of the write modes, a new file with the specified name is created.

Once the file has been opened, you can write text to it simply by specifying the data to be written as an argument to the fwrite() function.


// write to file
fwrite($fh, "Welcome to The Matrix, Neo") or die("Could not write to file");


Close the file, and you're done!

You can also write to a file with the new file_put_contents() function, which accepts a string as input and writes it to the named file with minimal fuss or muss.


// set file to write
$filename = "/tmp/matrix.txt";

// write to file
file_put_contents($filename, "Welcome to The Matrix, Neo") or die("Could not write to file");


>>> More PHP Articles          >>> More By icarus, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: