Welcome to Dream.In.Code
Getting Help is Easy!

Join 132,686 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,277 people online right now. Registration is fast and FREE... Join Now!




Reading, Writing, and Appending Files

 
Reply to this topicStart new topic

> Reading, Writing, and Appending Files, Like they taught in school, two Rs and an A

akozlik
Group Icon



post 25 May, 2008 - 11:38 PM
Post #1


While programming PHP applications, you may one day find yourself overcome with the desire to read, write, and edit text files. This tutorial is to help you achieve that life long dream. Here we'll cover the very basics of file editing, including the fwrite(), fread(), and fgets() functions.

First, the entire script:

CODE

<?php

// Function 1
function openFile($filename, $mode) {

  $fp = fopen($filename, $mode) or die ( mysql_error() );
  
  return $fp;

}

// Function 2
function writeFile() {

  $file = openFile("test.txt", "w");

  $text = "This has been written to the file";

  fwrite($file, $text);

  fclose($file);  

}

// Function 3
function appendFile() {

  $file = openFile("test.txt", "a");

  $text = "\nThis has been appended to the file";

  fwrite($file, $text);

  fclose($file);

}

// Function 4
function readTheFile() {

  $file = fopen("test.txt", "r");

  $filecontents = fread( $file, filesize("test.txt") );

  echo $filecontents . "<br /><br />";
  
  fclose($file);

}

// Function 5
function readFiveCharacters() {

  $file = fopen("test.txt", "r");
  
  $line = fread( $file, 5);
  
  echo $line . "<br /><br />";
  
  fclose($file);

}

// Function 6
function readLine() {

  $file = fopen("test.txt", "r");
    while ($line = fgets($file)) {
        echo $line . "<br />";
    }
  
  fclose($file);

}

writeFile();
appendFile();
readTheFile();
readFiveCharacters();
readLine();

?>



Function 1 - openFile():

This is a small function I wrote that attempts to open a file. If the file opening fails, the script halts on the die() function. If you are opening a file for writing, and the file does not exist, one is created for you. If a file is opened for reading but it doesn't exist, you will receive an error and the program will quit.

Function 2 - writeFile():

First we attempt to open the file, which won't be a problem because we're opening it with mode 'w'. When using the fopen() function to open a file, you pass two parameters. Your first parameter is the name of the file you are attempting to open. The second parameter is the mode in which you would like to open the file. The three we will be learning about are 'w', 'a', and 'r' which are write, append, and read, respectively. We could also use 'x' to force a fail if the file does not exist, despite the mode.

Opening the file in 'w' mode will place the file pointer at the beginning of the file. If the file previously existed, it will be overwritten. All data that was previously in the file will be deleted.

So we open the file for writing, and create a variable, $line, which holds the line of text we wish to write. We then call the fwrite() function with the file as the first parameter, and the text to be written in the second parameter. Finally, we call the fclose() function to close the file. This is very important to keep memory on the server free.

Function 3 - appendFile():

Again, we attempt to open the file. This time we're passing mode 'a'. This is what we use to append the text to the end of the file. If you wish to add data to the end of the file and keep from overwriting the previous data, this is the mode you want to use.

So again we set a $line variable and write it to the file. This time, the line is added to the end of the file. You can open the file and take a look, and you'll see that the text is written on the next line.

But wait! Take a look at that '\n' newline character. That adds a line break in the file. If you hadn't put that in, the file would just contain

This has been written to the fileThis has been appended to the file

Notice how it's all written on the same line? Remember your line breaks!

Function 4 - readTheFile():

First, it would have made more sense to name this function readFile() to keep in theme with the rest of the functions, but readfile() is a reserved function that comes with PHP. Hence readTheFile().

Anyway, again we open the file. Next, we call the fread() function. The first parameter is our file that we opened. The second parameter is the number of bytes you wish to read from the file. By calling filesize("test.txt"), we are asking to read the entire size of the file, which is the entire file.

Echoing out the file will display the entire file on one line. Remember, HTML does not process line breaks.

Function 5 - readFiveCharacters():

This function is almost the same as the above one, with a small difference. Rather than reading the entire file, we only read the first 5 bytes. One character is equivalent to one byte, so we are in effecting reading the first 5 characters. Echoing out the result will prove so. In this case, you will see 'This ' . Note that the space is counted as one character.

Function 6 - readLine():

Lets say you want to process the text file line by line. In this case you would want to use the fgets() function. fgets() will read the next line in the file every time it is called. In this function we want to read every line and print them to the browser.

Every time we call $line = fgets($file), fgets() puts the next line into the variable $line. We run the whole thing in a while loop which pulls each line from the file and prints it out, followed by a line break.

Conclusion:

That should be what you need to get started on file writing. Now you can go write a log analyzer, flat file database, or other crazy file editing program. As always, comments, suggestions, and corrections are available. If you want more information about each function, be sure to read the PHP Manual on php.net.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

jcarrott
*



post 23 Jul, 2008 - 08:04 AM
Post #2
QUOTE(akozlik @ 26 May, 2008 - 12:38 AM) *

While programming PHP applications, you may one day find yourself overcome with the desire to read, write, and edit text files. This tutorial is to help you achieve that life long dream. Here we'll cover the very basics of file editing, including the fwrite(), fread(), and fgets() functions.

First, the entire script:

CODE

<?php

// Function 1
function openFile($filename, $mode) {

  $fp = fopen($filename, $mode) or die ( mysql_error() );
  
  return $fp;

}

// Function 2
function writeFile() {

  $file = openFile("test.txt", "w");

  $text = "This has been written to the file";

  fwrite($file, $text);

  fclose($file);  

}

// Function 3
function appendFile() {

  $file = openFile("test.txt", "a");

  $text = "\nThis has been appended to the file";

  fwrite($file, $text);

  fclose($file);

}

// Function 4
function readTheFile() {

  $file = fopen("test.txt", "r");

  $filecontents = fread( $file, filesize("test.txt") );

  echo $filecontents . "<br /><br />";
  
  fclose($file);

}

// Function 5
function readFiveCharacters() {

  $file = fopen("test.txt", "r");
  
  $line = fread( $file, 5);
  
  echo $line . "<br /><br />";
  
  fclose($file);

}

// Function 6
function readLine() {

  $file = fopen("test.txt", "r");
    while ($line = fgets($file)) {
        echo $line . "<br />";
    }
  
  fclose($file);

}

writeFile();
appendFile();
readTheFile();
readFiveCharacters();
readLine();

?>



Function 1 - openFile():

This is a small function I wrote that attempts to open a file. If the file opening fails, the script halts on the die() function. If you are opening a file for writing, and the file does not exist, one is created for you. If a file is opened for reading but it doesn't exist, you will receive an error and the program will quit.

Function 2 - writeFile():

First we attempt to open the file, which won't be a problem because we're opening it with mode 'w'. When using the fopen() function to open a file, you pass two parameters. Your first parameter is the name of the file you are attempting to open. The second parameter is the mode in which you would like to open the file. The three we will be learning about are 'w', 'a', and 'r' which are write, append, and read, respectively. We could also use 'x' to force a fail if the file does not exist, despite the mode.

Opening the file in 'w' mode will place the file pointer at the beginning of the file. If the file previously existed, it will be overwritten. All data that was previously in the file will be deleted.

So we open the file for writing, and create a variable, $line, which holds the line of text we wish to write. We then call the fwrite() function with the file as the first parameter, and the text to be written in the second parameter. Finally, we call the fclose() function to close the file. This is very important to keep memory on the server free.

Function 3 - appendFile():

Again, we attempt to open the file. This time we're passing mode 'a'. This is what we use to append the text to the end of the file. If you wish to add data to the end of the file and keep from overwriting the previous data, this is the mode you want to use.

So again we set a $line variable and write it to the file. This time, the line is added to the end of the file. You can open the file and take a look, and you'll see that the text is written on the next line.

But wait! Take a look at that '\n' newline character. That adds a line break in the file. If you hadn't put that in, the file would just contain

This has been written to the fileThis has been appended to the file

Notice how it's all written on the same line? Remember your line breaks!

Function 4 - readTheFile():

First, it would have made more sense to name this function readFile() to keep in theme with the rest of the functions, but readfile() is a reserved function that comes with PHP. Hence readTheFile().

Anyway, again we open the file. Next, we call the fread() function. The first parameter is our file that we opened. The second parameter is the number of bytes you wish to read from the file. By calling filesize("test.txt"), we are asking to read the entire size of the file, which is the entire file.

Echoing out the file will display the entire file on one line. Remember, HTML does not process line breaks.

Function 5 - readFiveCharacters():

This function is almost the same as the above one, with a small difference. Rather than reading the entire file, we only read the first 5 bytes. One character is equivalent to one byte, so we are in effecting reading the first 5 characters. Echoing out the result will prove so. In this case, you will see 'This ' . Note that the space is counted as one character.

Function 6 - readLine():

Lets say you want to process the text file line by line. In this case you would want to use the fgets() function. fgets() will read the next line in the file every time it is called. In this function we want to read every line and print them to the browser.

Every time we call $line = fgets($file), fgets() puts the next line into the variable $line. We run the whole thing in a while loop which pulls each line from the file and prints it out, followed by a line break.

Conclusion:

That should be what you need to get started on file writing. Now you can go write a log analyzer, flat file database, or other crazy file editing program. As always, comments, suggestions, and corrections are available. If you want more information about each function, be sure to read the PHP Manual on php.net.

Go to the top of the page
+Quote Post

jcarrott
*



post 23 Jul, 2008 - 08:12 AM
Post #3
I am working in a .htm file, so I added this code after the Javascript code.

<script langauge=php>

function saveFile(strHtml) {
name = '/lawson/xhrnet/EmailStubs/' + authUser.employee + '_PayStub_' + CheckNum + '.html';
$file = openFile(name, "w");
$text = "This has been written to the file";
fwrite($file, $text);
fclose($file);
}

function openFile($filename, $mode) {
$fp = fopen($filename, $mode);
return $fp;
}


</script>

I received an error with your origianl code, that is why I removed the or die ( mysql_error() ). My code did not have a function mysql_error() and I did not know what you did in it.

I am now getting an 'object expected' error running the function openFile(). The file that is being opened does not exist, so it needs to be created.

Is the creation code in your mysql_error() code?
Go to the top of the page
+Quote Post

jam_altun_23
*



post 24 Jul, 2008 - 11:54 AM
Post #4
Thanks for this tutorial.
I like it. It is simple and understandable for me and I think everyone...
Go to the top of the page
+Quote Post

akozlik
Group Icon



post 24 Jul, 2008 - 11:56 AM
Post #5
QUOTE(jam_altun_23 @ 24 Jul, 2008 - 03:54 PM) *

Thanks for this tutorial.
I like it. It is simple and understandable for me and I think everyone...


Cool, glad you like it. I have a bunch of others around the PHP Tutorial section so check 'em out.
Go to the top of the page
+Quote Post

mahendra_22patil
*



post 17 Aug, 2008 - 11:54 PM
Post #6
QUOTE(akozlik @ 24 Jul, 2008 - 12:56 PM) *

QUOTE(jam_altun_23 @ 24 Jul, 2008 - 03:54 PM) *

Thanks for this tutorial.
I like it. It is simple and understandable for me and I think everyone...


Cool, glad you like it. I have a bunch of others around the PHP Tutorial section so check 'em out.



hi friend
how to delete content of text file using PHP rolleyes.gif ???????
Go to the top of the page
+Quote Post

akozlik
Group Icon



post 18 Aug, 2008 - 11:31 AM
Post #7
QUOTE

hi friend
how to delete content of text file using PHP rolleyes.gif ???????


Post the question in the PHP forum and I'll check it out. It'll also get more publicity there, so your chances of getting a quick answer are better. When you post make sure you describe precisely what you're trying to do. Deleting context of a text file is pretty broad. Thanks.
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 11/23/08 07:18AM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month