FireFox! The PHP Forum Loans and Credit
Panama Web Design for Hire Free Insurance Quotes!
Web Hosting Advertise Here $10 a Month Designer Children
Never Pay Taxes Again HGH Domain name registration
Web Hosting and Dedicated Servers Insurance Affordable web-hosting


HomeWatched TopicsRegisterSearchDirectory
FAQMemberlistUsergroupsLog inStoresItemsBank
Google

Reply to topic Page 1 of 1
Working with text files
Message  

Reply with quote
Post Working with text files 
Introduction
Welcome to my tutorial on "Working with text files"!

When you have an idea to design a website that has the ability to handle data inside it, normally you start off the project planning the database type, database structure, etc. Normally, the database type depends on the amount of records you'll handle and how often you will be accessing those records.

Depending on the amount of records, there are basically two ways of storing data: in a structured database or in a simple text file.

If you are dealing with information of a reasonable amount of volume, such as, information of registered members in your site, you'll need a database. But, there will be situations where you need to know how to work with text files and get use of them. I will provide some useful examples as we work through this tutorial.

Is working with a text file easier than working with a database?
Working with text files is a very simple thing to do in PHP scripts. Database programming is also not a hard job. However, text files are a good starting place for novice programmers. In this tutorial I hope to teach you, how to:

1. Open a text file.
2. Write data into a text file.
3. Close a text file.
4. Read from a text file.
5. Delete text files.
7. Other functions regarding text files.
8. An example & summarizing tutorial.
9. Advanced examples:
* Update selected rows in a text file
* Deleting rows in a text file
* Searching rows in a text file

Now let's go through the tutorial, step by step!

Source: http://codewalkers.com/tutorials/57/1.html

View user's profile Send private message

Reply with quote
Post  
Opening a text file
The first thing to do is to open a text file in your web directory. To open a text file, the file should exist in the given path. In the file you are trying to open can't be found, you can have PHP to create a new one for you.

To open a file in PHP, we simply use fopen() function. At the point we open the selected file, we need to specify how we intend to use it after opening. So, that means before opening a file using PHP's fopen(), we need to plan for what type of purposes we hope to use the opened file. This is called "File mode".

File Modes :
* Opening a file for reading only, for writing only or for both.
* When you write to the file, you might want to overwrite current data in it or write new data without overwriting existing.

fopen() function
When fopen() is called, there are two parameters. The first parameter should be the file you want to open. You can specify a directory path to this file as shown below:

<?php
$fp = fopen( "notes/data/names.txt" , "w" );
?>  


The second parameter of this function is the file mode. This parameter indicates what you are planning to do with the opened file. In above case we are using "w", so that means open the file for writing.

For more information about file modes : http://us2.php.net/manual/en/function.fopen.php

If fopen() opens the file successfully, a pointer to the file is returned and will be stored in a variable, in above case $fp. You must use that variable whenever you want to work with the opened file.

When an error occurs while calling fopen() the function returns false. You could handle this error situation in a user-friendly way.

<?php
$fp = fopen( "notes/data/names.txt", "w" );

if(!$fp)
{
    echo "Couldn't open the data file. Try again later.";
    exit;
}
?>  


Source: http://codewalkers.com/tutorials/57/2.html

View user's profile Send private message

Reply with quote
Post  
Writing data into a text file
You may think writing into a text file using PHP functions is hard. Actually it is easier than you think. By using the fwrite() function or fputs() function, PHP writes data to the opened file. fputs() is an alias to fwrite().

<?php
$fp = fopen( "notes/data/names.txt" , "w" );
$inputString = 'Some text';
fwrite( $fp, $inputString );
?>  


This tells PHP to write the string stored in $inputString to the file pointed to by $fp.
Here is a another simple example of using fwrite() and hopefully, you would get an understanding about the parameters.

<?php
$inputString = "This is the first line.\nThis is the seconds line.\nThis is the third line.";

$fp = fopen( "notes/data/names.txt" , "w" );
fwrite( $fp, $inputString );
?>  


Source: http://codewalkers.com/tutorials/57/3.html

View user's profile Send private message

Reply with quote
Post  
Closing a text file
When you've finished using the opened file, you must close it before you move on to new work. It is an easy function with one parameter to be passed, the file pointer which was used when opening the file.

<?php
fclose( $fp );
?>  


So, there is nothing much to talk about this function. We shall sum up the content we learnt to this point with the following example:

<?php
$inputString = "This is the first line.\nThis is the seconds line.\nThis is the third line.";

$fp = fopen( "notes/data/names.txt" , "w" );
fwrite( $fp, $inputString );

fclose( $fp );
?>  


Source: http://codewalkers.com/tutorials/57/4.html

View user's profile Send private message

Reply with quote
Post  
Reading from a text file
The most common way of reading from a text file is to use the fread() function though there are many other ways to read as well. We will discuss about other functions in a later chapter of this tutorial. To get a reasonable understanding of this part, we'll talk about fread() here.

To read a file, there should be a variable with a pointer to a opened file which we mentioned in last few chapters. This is the common syntax of this function.

<?php
$content = fread( $fp, filesize( $filename ) );
?>  


The first parameter is, as usual, a pointer to a file. Second parameter is the number of bytes that should be read in by the function. Usually, when we need to read the whole file, we use the filesize() function to help this matter. It will return the total bytes of the given file. So, then fread() gets its second parameter as total number of bytes. It places the content of the whole file pointed by $fp in the $content variable. You may use $content to do any type of processing as now it has the all ingredients of the file.


Source: http://codewalkers.com/tutorials/57/5.html

View user's profile Send private message

Reply with quote
Post  
Deleting a file
If you want to delete a file after working with it, use the unlink() function. This function only accepts one parameter, a filename of the file you want to be removed.

<?php
unlink( "notes/data/names.txt" );
?>  


This function returns true if the file was successfully deleted and returns false if not. An error typically occurs only when you do not have permission to delete the file or when the given file was not found.

Source: http://codewalkers.com/tutorials/57/6.html

View user's profile Send private message

Reply with quote
Post  
Other functions regarding text files
There are a few other functions which we did not talk about in previous chapters. We can learn about them one by one in this chapter.

fgets()
In case you want to read a file one line at a time, this is what you need.

<?php
$buffer = fgets( $fp, 100);
?>  


In this case, this script will read until it finds a new line character (\n), encounters an EOF, or has read 99 bytes from the file. The maximum length read is the length specified minus one byte. The fgets() function is useful when dealing with files that contain plain text that we want to deal with in chunks.

http://us2.php.net/manual/en/function.fgets.php

feof()
This function takes file pointer as its single parameter. It will return true if the file pointer is end of file and false if it is somewhere else in the file. We commonly use this function when looping through a file until the end of file.

<?php
while (!feof( $fp ))
?>  


http://us2.php.net/manual/en/function.feof.php

An example:

<?php
$fp = fopen ("notes/data/names.txt", "r");
while (!feof ($fp)) {
    $content = fgets( $fp, 4096 );
    echo $content;
}
fclose ($fp);
?>  


The above example simply outputs the content in the text file which is opened in the first line of the script. This uses the feof() function which is mentioned above and it read the file until EOF file occurs. While running the loop it echos the content read line by line fgets() function!

readfile()
Instead of reading line by line, we can read the whole file in one go with readfile(). Secondly this automatically echos the contents of the file to the browser without adding echo() or print(). Unlike other functions this takes the parameter of filename with the path of it, not a file pointer.

<?
readfile( "notes/data/names.txt" );
?>  


http://us2.php.net/manual/en/function.readfile.php

file()
This is a very important function when it comes to file reading. It also identical to the readfile() except that instead of echoing the file as an output, it turns it into an array. Elements of the array will be the lines of the opened file. We'll go through this function with more details in examples at the end of the tutorial.

<?php
$arrContent = file( "notes/data/names.txt" );
?>  


http://us2.php.net/manual/en/function.file.php

file_exists()
Just to check whether given file exists, simply use it like this.

<?php
$filename = "notes/data/names.txt";
if(file_exists( $filename ))
    echo "The file $filename exists.";
else
    echo "The file $filename does not exists.";
?>  


http://us2.php.net/manual/en/f...exists.php

filesize()
I hope you can remember we used this function when we were reading the file with fread(). You can check the size of a file in bytes like this.

<?php
$filename = "notes/data/names.txt";
echo "$filename is ". filesize( $filename ). " bytes big.";
?>  

Source: http://codewalkers.com/tutorials/57/7.html

View user's profile Send private message

Reply with quote
Post  
An example & summarizing tutorial
Imagine you have to create a mailing list for your site visitors. When we plan this process these are the normal steps which we need to concentrate on:

1. Creating a HTML form to input email addresses of visitors. (input.htm)
2. PHP page to receive the email address from the HTML page and write them in a text file. (submit.php)
3. Read the text file and send an email to all subscribers. (send.php)

We'll start off the project by stepping on to the first one. Create a simple HTML form with one text field and a submit button.

input.htm
<html>
<head>
<title>Subcribe</title>
</head>
<body>
<form name="subscribe" action="submit.php" method="post">
Enter your email address : <input type="text" name="emailadd" /><br />
<input type="submit" name="submit" value="Subscribe" />
</form>
</body>
</html>  


This will post the email address to the submit.php. What are we waiting for? We can also code it now as you have already learnt all the functions you'll be experiencing on this page.

submit.php
<?php
$emailAddress = $_POST['emailadd'];

if(!$emailAddress) // If email address is not entered show error message
{
    echo "Please enter your email address.";
    exit;
}
else
{
    $filename = "subscribers.txt"; // File which holds all data
    $content = "$emailAddress\n"; // Content to write in the data file
    $fp = fopen($filename, "a"); // Open the data file, file points at the end of file
    $fw = fwrite( $fp, $content ); // Write the content on the file
    fclose( $fp ); // Close the file after writing
    
    if(!$fw) echo "Couldn't write the entry.";
    else echo "Successfully wrote to the file.";
}
?>  


That's it. I hope you could understand the process with the help of comments written inside the code. This code simply checks whether user has entered an email address. Then if he hasn't entered, it shows an error message, or if he has entered an address, it writes it into the text file where all the addresses are stored.

The next part of the project is retrieving all email addresses in the file and sending emails to all of them. Let's go through that part and sum up the project now.

send.php
<?php
$filename = "subscribers.txt"; // File which holds all data
$arrFp = file( $filename ); // Make array of file content lines
$numAdds = count( $arrFp ); // Count no. of elements in the array, count email addresses

for($i=0; $i<$numAdds; $i++)
{
    $emailAddress = trim( $arrFp[$i] ); // Trim email addresses before sending mails
    echo "Sending email to $emailAddress...";
    $success = mail( $emailAddress, "Test email", "This is a test email message");
    
    if($success) echo "Success<br>";
    else echo "Error<br>";
}
?>  

Source: http://codewalkers.com/tutorials/57/8.html

View user's profile Send private message

Reply with quote
Post  
Advanced examples
Update selected rows in a text file
<?php
$filename = "data.txt"; // File which holds all data
$rowToUpdate = 1; // This is line need to be updated
$newString = "This text is updated\n"; // This is what you want to replace it with

$arrFp = file( $filename ); // Open the data file as an array
// Replace the current element in array which needs to be updated with new string
$arrFp[$rowToUpdate-1] = $newString;
$numLines = count( $arrFp ); // Count the elements in the array

$fp = fopen( $filename, "w" ); // Open the file for writing
for($i=0; $i<$numLines; $i++) // Overwrite the existing content
{
    fwrite($fp, $arrFp[$i]);
}
fclose( $fp ); // Close the file
?>  


In this example, first, the script opens a text file as an array. Then it replaces the array element which is relative to the row you want to update with the new string. Finally, the script again writes the elements of the array (text file lines) to the same text file, replacing the existing content. After closing the file, you could check your text file and you’ll notice that the line you wanted to update has been replaced by the value stored in $newString.

Delete selected rows in a text file
<?php
$filename = "data.txt"; // File which holds all data
$rowToDelete = 1; // This is line need to be deleted

$arrFp = file( $filename ); // Open the data file as an array
$numLines = count( $arrFp ); // Count the elements in the array

$fp = fopen( $filename, "w" ); // Open the file for writing
for($i=0; $i<$numLines; $i++) // Overwrite the content except the line to be deleted
{
    if($i != ($rowToDelete-1) )
    fwrite($fp, $arrFp[$i]);
}
fclose( $fp ); // Close the file
?>  


Here you’ll find a way to delete a selected line from a text file using PHP codes. As usual, this opens a text file into an array with the use of file() function which I noted as a “very important function when it comes to file reading”. I hope you’ll see it in these examples. After making an array of lines, the script simply runs a loop of the array as it writes the elements into the same text file, except the line which you wanted to delete. Simple as that!

Searching for restricted words
<?php
$filename = "data.txt"; // File which holds all data
$inputString = "This is where you need to put some string which has bad words.";

$arrFp = file( $filename ); // Open the data file as an array
$numLines = count( $arrFp ); // Count the elements in the array

$arrWords = explode( ' ', $inputString ); // Split the input string into words as an array
$numWords = count( $arrWords ); // Count the words in the string

for($i=0; $i<$numWords; $i++) // Loop through the words in the string
{
    for($j=0; $j<$numLines; $j++) // Loop through the lines of the text file
    {
        if(strstr($arrWords[$i], trim( $arrFp[$j] ))) // Search whether the current words is restricted
            $arrWords[$i] = "*****"; // If it is replace the word with asterisks
    }
    
    $outputString .= $arrWords[$i].' ';
}
echo $outputString; // Echo the string replacing restricted words

?>  


This is a common situation which many of the webmasters have to face when some type of posting can be done in their sites. You should restrict words which is not suitable to be displayed in your site. You should store your restricted words list in a simple text file, line by line to start with. Then open the text file as an array. At the same time, split your string which includes the bad words into separate words. Write two loops one inside the other. First one is to loop through the words in your posted string and the second loops through the array which has the restricted words. While running the loop check whether the current word is a restricted word, replace the current word with few asterisk signs. Finally, when you echo the output it will show the posted string, with restricted words in asterisk marks. Handsome code!


Source: http://codewalkers.com/tutorials/57/9.html

View user's profile Send private message
Display posts from previous:
Reply to topic Page 1 of 1
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
  



Google

FireFox! The PHP Forum Loans and Credit
Panama Web Design for Hire Free Insurance Quotes!
Web Hosting Advertise Here $10 a Month Designer Children
Never Pay Taxes Again HGH Domain name registration
Web Hosting and Dedicated Servers Insurance Affordable web-hosting


Web Design by PlatinumShore.com & Web Hosting by TradeWebHosting.com