Jump to content

cbox


Beginning PHP - Lesson 19 - Reading External Files into PHP


fattwam

Recommended Posts

Posted

Now that we know how to read and write to files, lets make something. Do you remember the simple "Chat System" from lesson 11? Lets turn it into a REAL chat system. (One that won't forget the messages!) So open SciTE (or Notepad) and type the following into it:

(Do NOT copy and paste the code! You need to learn it and typing it will help you to focus on it.)

 

[code]<?php

/////////////////////////////////////////////////////////////////////////
// Put the page layout in some strings:

$filename = "chatfile.txt";
$startofpage = "<html><body>
<BR><BR><center><Table border="1"><tr><td>";
$endofpage = "</td></tr></table></center></body><html>";
$form = "<form action="" method="post">
	<textarea name="text" rows="4" cols="60"></textarea>
	
<input name="submit" type="submit" value="Submit">
	</form>";

/* 
Now that we have a basic layout in a few strings
we can move onto writing the code. 
*/
/////////////////////////////////////////////////////////////////////////


if (isset($_POST['text'])) {

///////////////////////////////////////
// Clean the text from HTML, PHP, and Cussing
$text = strip_tags(trim($_POST['text']));
$badwords = array("sucks", "damn", "#!@?", "ASP");
$text = str_replace($badwords, "****", "$text");
$text .= ":END:n"; 
///////////////////////////////////////





////////////////////////////////////////////////////////////
// We create the filehandle and set the mode to write ("a")
$filehandle = fopen($filename, 'a') or die('Could not open the file');
if (!fwrite($filehandle, $text)) {
	echo "Could not add the post to the file!";
} else {
	echo "<BR><font color="red">Added your comment!</font><BR>";
}

fclose($filehandle);
////////////////////////////////////////////////////////////

}


/////////////////////////////////////////////////////////////////////////
// Now we need to open the file back up and pull out all of the comments.
$contents = file($filename);

if (count($contents) >= 1) { 

foreach ($contents as $row)
{
   $comment = str_replace(":END:", "<HR>", $row);
   $comment = str_replace("n", "<BR>", $comment);
   $usercomments .= $comment;
}  
}
/////////////////////////////////////////////////////////////////////////




/////////////////////////////////////////////////////////////////////////

if (!isset($usercomments)) {
$usercomments = "There are no comments";
}
$usercomments = "<BR><BR><div align="left" border="1">". $usercomments. "<div>
";



echo $startofpage;
echo $usercomments;
echo $form;
echo $endofpage; 


?>[/code]

 

When you are done typing in that code, save it as "chatscript.php" and upload (FTP) it to your web server. Before you go on, try to just read through the code and see if you can follow the logic. Then run it a couple of times and post different things and see if you can understand most of the code.

 

 

 

 

Now here is the break-down of the script:

 

1) We start by putting the layout, filename, and comment form into strings so that we can keep our code clean by just using a string instead of putting all of that code into our loops...

[code]<?php

/////////////////////////////////////////////////////////////////////////
// Put the page layout in some strings:

$filename = "chatfile.txt";
$startofpage = "<html><body>
<BR><BR><center><Table border="1"><tr><td>";
$endofpage = "</td></tr></table></center></body><html>";
$form = "<form action="" method="post">
	<textarea name="text" rows="4" cols="60"></textarea>
	
<input name="submit" type="submit" value="Submit">
	</form>";

/* 
Now that we have a basic layout in a few strings
we can move onto writing the code. 
*/
/////////////////////////////////////////////////////////////////////////
?>[/code]

 

 

 

 

 

 

2) Next we check to see if anything was POSTED to the page. This will evaluate to FALSE if nothing has been "Posted" to the page (and FALSE means that it won't run).

However, after something has BEEN posted then this will be TRUE and the loop will run:

[code]<?php

if (isset($_POST['text'])) {

///////////////////////////////////////

// Clean the text from HTML and PHP So that no one messes up the page!
// trim() deletes the white spaces at the end of a string.
$text = strip_tags(trim($_POST['text']));

// Make an array called $badwords that has bad words as each array element
$badwords = array("sucks", "damn", "#!@?", "ASP");
// Then we replace all of the matching bad words in $text with "****"
$text = str_replace($badwords, "****", "$text");

// We need to add something that we can split the text with:
$text .= ":END:n"; 
/*
The ( . ) char before the "=" means "add to $text", and the "n" is the text version of pressing "Enter" on the keyboard. We added the "n" so that each comment will be on a different line in the file.
*/
///////////////////////////////////////

?>[/code]

 

After we determined that a message was posted we then clean the message of all of the PHP, HTML, and Cussing that could ruin our conversation or point to spam sites. Finally we add ":END:n" to the end of the text so that we can tell each comment apart.

 

 

 

3) Now that we have the cleaned message ready, we open the file and write the new text to it:

[code]<?php

////////////////////////////////////////////////////////////
// We create the file handle and set the mode to write ("a")
$filehandle = fopen($filename, 'a') or die('Could not open the file');

// Now we take the new comment and put it into the text file.
if (!fwrite($filehandle, $text)) {
	echo "Could not add the post to the file!";
} else {
	echo "<BR><font color="red">Added your comment!</font><BR>";
}

fclose($filehandle);
//Then close the file
////////////////////////////////////////////////////////////

}

?>[/code]

For those of you who don't know loops (read the lessons on them) I am going to write the [if][/i] loop in English:

 

[code]<?php
if (!fwrite($filehandle, $text)) {
	echo "Could not add the post to the file!";
} else {
	echo "<BR><font color="red">Added your comment!</font><BR>";
}

// Would look like this to a human:

if You(CANNOT write the $text to the file) {
	tell the user: "Could not add the post to the file!";
} otherwise if you COULD write to the file {
	tell the user: "<BR><font color="red">Added your comment!</font><BR>";
}
?>[/code]

 

 

 

 

4) Now that we just finished checking to see if a message was posted it is time to show all of the messages in the file:

[code]<?php


/////////////////////////////////////////////////////////////////////////
// Now we need to open the file back up and pull out all of the comments.

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


//if the array isn't empty (a.k.a. there was something in the file!)
if (count($contents) >= 1) { 

// Loop through the array and after fixing each row 
// add the fixed array element to the $usercomments string
foreach ($contents as $row)
{
	/* 
	First we need to separate the comments by Replacing
	any :END:'s with a <HR>. 
	*/
   $comment = str_replace(":END:", "<HR>", $row);
   /*
	Then we replace any "newline"
	chars (n) with a 
so that if someone presses Return
	in the textarea the new line will show up right when we show 
	the comment.
	*/
   $comment = str_replace("n", "<BR>", $comment);
   // ADD the finished array element to the $usercomments 
   // string and start the loop over:
   $usercomments .= $comment;
}  
}
/////////////////////////////////////////////////////////////////////////

?>[/code]

In English the if loop would read:

 

[code]<?php
if the(number of array elements in "$contents" is greater than or equal to 1) { do this:
foreach (of the elements in "$contents", put that element in a var called "$row")
{
...[do the code HERE]....
} Now that we are done with that array element empty "$row" and go to the next element.
}
?>[/code]

 

 

 

 

 

5) After we have grabbed all of the comments out of the file we just need to make another "safety" loop that will print "There are no comments" if for some reason the file is empty:

(Note: This is just a nice thing to add)

[code]<?php

/* 
If $usercomments has not been set then there are no comments! Because the loop
was never run (it equaled FALSE) and so the variable "$usercomments" was never made!
so lets make the $usercomments string and put a warning sentence in it.
*/
if (!isset($usercomments)) {
$usercomments = "There are no comments";
}

?>[/code]

 

 

 

 

6) Finally, We add some formatting to the comments so that they stay in a box. and print everything to the screen!

[code]<?php

// Lets add some formatting to the comments:
$usercomments = "<BR><BR><div align="left" border="1">". $usercomments. "<div>
";

/////////////////////////////////////////////////////////////////////////
// Now just show the finished result:
echo $startofpage;
echo $usercomments;
echo $form;
echo $endofpage; 
/////////////////////////////////////////////////////////////////////////

?>[/code]

 

 

Wow, good job! You finished it! (It took me ALL DAY to write this lesson!) Doesn't it feel good to have made something cool?!

 

Now I hope you followed the code and can now understand all of the loops and functions in it (If you are having trouble review the past lessons). If you just take code in small pieces it is a LOT easier to understand, so don't let anything intimidate you!

 

 

(Note: You can download the script at the bottom.)

 

##########################################################

## Another Chat Script!

##########################################################

 

Well, for those of you who want to make a more advanced chat system here is another script that allows you to enter your name, email, message, and the date! Now that you have finished the above script you shouldn't have very much trouble understanding this one.

 

Also, there are a couple of NEW functions in this script - don't panic - just stop by php.net, type the name of the function (such as "list()")in the search box, and they will show you what it is and tell you about it. Have a great day!

 

[code]<?php

// lets put our file into an variable ....
$file = 'chatfile2.txt';
// Max size in bytes that you want the Chat file to reach!
$filesize = 400000;





//////////////////////////////////////////////////////////////////

/* 
This is the code that checks to see if something was "POST" 'ed 
and that it is a real message. Also clears out any code that may 
have been entered by a user (strip_tags(); ). 
*/

if ((isset($_POST["name"])) && (isset($_POST["msg"])) && (isset($_POST["email"])) 
&& ($_POST["name"]!="") && ($_POST["msg"]!="") && ($_POST["email"]!="")) {


$email = strip_tags($_POST["email"]);
$msg = strip_tags($_POST["msg"]);
$name = strip_tags($_POST["name"]);

$email = str_replace("|", "", $email);
$msg = str_replace("|", "", $msg);
$name = str_replace("|", "", $name);

$date = date("F j, Y, g:i a");



/* 
If the code is good then enter it into the file along 
with the other messages from other users. 
Remember that the variable "$file" means the file you are writing too.
*/


$content = "$name|$email|$msg|$daten"; 
// Add a newline char ("n") so that each comment is on a new line. 


if (filesize($file) < $filesize) {
$handle = fopen($file, 'a');
fwrite($handle, $content);
fclose($handle);
echo "
Your Message Has Been Added
";
} else {
echo "File Is to Full";
}



} // End the IF posted loop...


//////////////////////////////////////////////////////////////////






//////////////////////////////////////////////////////////////////

/*
This is the code that opens the file and organizes
and prints out the messages that other people left.
*/


$handle = fopen($file, "r");

if (!(filesize($file) == 0)) {

while (!feof($handle)) {
	$line = fgets($handle, 5096);
	@list($user_name, $user_email, $user_msg, $user_date) = explode("|", $line);
	
	echo '<table border="2"><tr id="350"><td><p>Name: '. $user_name.
	'</td><td>Email: '. $user_email. 
	'</td></tr><tr><td colspan="2">Message: '. $user_msg.
	'</td></tr><tr><td colspan="2">Date: '.$user_date.
	'</td></tr></table>
';
}
} else { 
echo "File is empty";
}

fclose($handle);


////////////////////////////////////////////////////////////////////




/* This is the "FORM" at the bottom of the page used to "Submit" messages to this file */

echo '<BR><BR><hr><hr><form action="" method="post"><table>

<tr><td>Your Name:</td><td><input type="text" name="name" /></td></tr>
<tr><td>Your Email:</td><td><input type="text" name="email" /></td></tr>
<tr><td>Message:</td><td><textarea name="msg" rows="5" cols="30"  maxlength="1000">Enter Text</textarea></td></tr>
<tr><td><input type="submit" value="Submit"/></td></tr>

</table></form>';


?>[/code]

 

 

You can download both scripts here:

Lesson 19 Files

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...