Code2Design.com

User login

The Layout

Programming

Graphic Design

Resources

Navigation

C2D Projects

Unsystematic Affiliates

The-Tutorials Fresh Tuts PhotoShop Aid Capital Tutorials 

Change Language

Who's online

There are currently 0 users and 7 guests online.

Lesson 18 - Reading External Files into PHP - Part 3

Now that we know how to read data from files into arrays, strings, and variables, lets try writing to files. Writing to files is pretty much the same as reading from them:

1) First you put the file name/path in a variable so that we can tell the computer what file we want edited (We can it "the file handle").
2) Then we open the file.
3) Now instead of reading from the file we write to the file.
4) Finally we close the file.

Open up you text editor (SciTE I hope) and type the following into it. When you are done, upload it to your web server.

<?php
// 1) Store the file name in a string (this is the file handle).
$filename "writetest.txt";
// 2) Open the file
$filehandle fopen($filename'w');
// 3) Write what we want to the file
fwrite($filehandle"This goes in the file.\n");
// 4) Close the file
fclose($filehandle);
?>

(Note: if you don't see anything when you browse to the file, it worked. You won't see anything because we don't "echo" or "print" anything in this script; all we do is write to a file.)

One thing you might notice is that in addition to the script writing to the file, the script also CREATED the file! The "w" command that we put in the fopen function ( fopen($filename, 'w') ) means this to the computer: "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."

Now if you open "writetest.txt" you will see this in it:

This goes in the file.

And there you have it! I told you it was just as easy to write to files! :)

Now lets modify the file to create five lines of text, we will put them on different lines using the "next line" (\n) character:

<?php
// Put the text we want in the file in a string.
$text "This is line one.\nThis is line two.\nThis is line three.\nThis is line four.\nThis is line five.\n";

// 1) Store the file name in a string (this is the file handle).
$filename "writetest.txt";
// 2) Open the file
$filehandle fopen($filename'w')
// 3) Write what we want to the file
fwrite($filehandle$text);
// 4) Close the file
fclose($filehandle);
?>

Now after running the file you will see this in writetext.txt:

This is line one.
This is line two.
This is line three.
This is line four.
This is line five.

Peace of cake, huh? 8)

To finish off our file lets delete the comments in the code (you can keep them if you want) and add a couple of error checking functions - just so you learn to code properly. First lets add a "die" command to the fopen function:

<?php
$text 
"This is line one.\nThis is line two.\nThis is line three.\nThis is line four.\nThis is line five.\n";
$filename "writetest.txt";
$filehandle fopen($filename'w') or die('Could not open the file');
fwrite($filehandle$text);
fclose($filehandle);
?>

The or die command just means:
If there is an error: stop the script and display [i]this message instead of a cryptic PHP error message.[/i]
Feel free to change "Could not open the file" to anything you want the error to say. You can test it by putting an error like this in the code:

$filehandle = fopen($filename22222, 'w') or die('Could not open the file');

Second lets add a message that lets us know that everything went all right. (First fix the error you just made :wink:

<?php
$text 
"This is line one.\nThis is line two.\nThis is line three.\nThis is line four.\nThis is line five.\n";
$filename "writetest.txt";
$filehandle fopen($filename'w') or die('Could not open the file');

if (!
fwrite($filehandle$text)) {
    echo 
"Could Not write to the file!";
} else {
    echo 
"Wrote the following to the file:<BR>$text";
}

fclose($filehandle);
?>

For those of you who don't know; this is an if statement. Lets take it line by line to make it easier to understand:

<?php
if (!fwrite($filehandle$text)) {
    echo 
"Could Not write to the file!";
?>

In english it reads:
if (you cannont write (!fwrite) the value of "$text" to "writetest.txt") {
print "Could Not write to the file!"

Basically, if something goes wrong and you CANNOT write to the file, tell the user.

Here is the next part that will run if the first part of the loop is false:

<?php
} else {
    echo 
"Wrote the following to the file:<BR>$text";
}
?>

This else statement will ONLY run if the first part ("if could not write") is false. If this does run then that means that the script COULD write to the file! Along with letting the user know that everything is OK, we print out the value of what we put in the file ($text).

##################################################
## Checking Files
##################################################

Now lets practice with some of the other functions made for files:

is_file() - returns True/False indicating whether the specified file is a regular file
is_executable() - returns True/False indicating whether the specified file is executable
is_readable()- returns True/False indicating whether the specified file is readable
is_writable()- returns True/False indicating whether the specified file is writable
filesize() - gets size of file
filemtime() - gets last modification time of file
filetype() - gets file type

(Note: you can find ALL of the functions for files at php.net)

Lets put each one to use in a new script; type this into you editor:

<?php
$filename 
"writetest.txt";

if (
is_file($filename)) { echo "$filename is a File!<br>"; }

if (
is_executable($filename)) { echo "$filename is executable!<br>"; }

if (
is_readable($filename)) { echo "$filename is readable!<br>"; }

if (
is_writable($filename)) { echo "$filename is writable!<br>"; }

echo 
" $filename is "filesize($filename). " bytes<br>";

echo 
"$filename was last modified: " date ("F d Y H:i:s."filemtime($filename)). "<br>";

echo 
"$filename is a "filetype($filename). " file<br>";
?>

Notice that every function except for is_executable was true. That is because ".txt" files are just plain text files - they are not programs.

###############################################
## Extra Information about the echo statements
###############################################

Another thing that might throw you off are the periods ( . ) in some of the echo statements. Such as:

<?php
echo " $filename is "filesize($filename). " bytes<br>";
?>

These periods are a way to add different kinds of things to an echo. As you know a normal echo looks like this:

<?php
echo "Hello World";
?>

You can also echo functions like this:

<?php
echo filetype($filename);
?>

However, when you want to echo the results of a function within a sentence you can't do this:

<?php
echo "Hello World, filetype($filename)";
?>

All you would see is "Hello World, filetype(writetest.txt)" if you ran it. And if you tried to end the text ( put a closing ")and then put in the function you would get a parse error:

<?php
echo "Hello World" filetype($filename);
// gives you a parse error!!!
?>

This is where ( . ) enters in, they tell the computer that there is more coming in the echo command:

<?php
echo "$filename is "filesize($filename). " bytes<br>";
?>

In English this code would read:

print {{Start of Text}} (the value of "$filename") is {{End of Text}} plus ( . ) (print the size of "$filename") plus ( . ) {{Start of Text}} bytes<br> {{End of Text}};

Phew!!!! I am tired after all of this, Later! 8)


Submitted by David on November 10, 2006 - 8:01pm.
printer friendly version

Error..

On the second file write code:

<?php
// Put the text we want in the file in a string.
$text "This is line one.\nThis is line two.\nThis is line three.\nThis is line four.\nThis is line five.\n";

// 1) Store the file name in a string (this is the file handle).
$filename "writetest.txt";
// 2) Open the file
$filehandle fopen($filename'w')
// 3) Write what we want to the file
fwrite($filehandle$text);
// 4) Close the file
fclose($filehandle);
?>

I get this error..
Parse error: syntax error, unexpected T_STRING in C:\Program Files\VertrigoServ\www\code2design\phplessons\filehandle.php on line 10


No end semicolon

When you get a message like that you need to look at line 10 and the last line before it for any (small) mistakes you could have made. In this case there is no end semicolon (;) on line 8, causing the next line (10) to start wrong.


The mistake isn't Line 10

The mistake is in Line 8, put a ; at the end of Line 8.

EDITED: The person before me corrected it first, sorry....LOL


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