Code2Design.com

User login

The Layout

Programming

Graphic Design

Resources

Navigation

C2D Projects

Unsystematic Affiliates

Tutorial Mix Tutorial Index GameXe Glitch Seekers 

Change Language

Who's online

There are currently 0 users and 15 guests online.

Lesson 19 - Reading External Files into PHP - Part 4

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.)

<?php
/////////////////////////////////////////////////////////////////////////
// Put the page layout in some strings:

$filename "chatfile.txt";
$startofpage "<html><body><br><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>
        <br><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><br>";
   
   
   
    echo 
$startofpage;
    echo 
$usercomments;
    echo 
$form;
    echo 
$endofpage
?>

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...

<?php
/////////////////////////////////////////////////////////////////////////
// Put the page layout in some strings:

$filename "chatfile.txt";
$startofpage "<html><body><br><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>
        <br><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. 
*/
/////////////////////////////////////////////////////////////////////////
?>

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:

<?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.
    */
    ///////////////////////////////////////
?>

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:

<?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
    ////////////////////////////////////////////////////////////
   
}
   
?>

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:

<?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>";
    }
?>

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:

<?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 <br> 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;
    } 
}
/////////////////////////////////////////////////////////////////////////
?>

In English the if loop would read:

<?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.
}
?>

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)

<?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";
}
   
?>

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

<?php
   
// Lets add some formatting to the comments:
$usercomments "<BR><BR><div align=\"left\" border=\"1\">"$usercomments"<div><br>";
   
/////////////////////////////////////////////////////////////////////////
// Now just show the finished result:
   
echo $startofpage;
    echo 
$usercomments;
    echo 
$form;
    echo 
$endofpage
/////////////////////////////////////////////////////////////////////////
?>

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!

<?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|$date\n"
   
// 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 
"<br>Your Message Has Been Added<br>";
    } 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($handle5096);
        @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><br>';
    }
} 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>'
;
?>

You can download both scripts bellow.

AttachmentSize
C2D_Lesson_19.zip2.36 KB

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

adding smileys

After this....

<?php
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");


?>

add the following....

<?php

// put the smile keys(the symbols people type for smileys)into an array 

$smilekey = array(":)"":P"";)"); 

/*
put the url's of your smile images and html format to display them into
an array, making sure they are in the same sequence as the smile keys.
Change the url to wherever you have your images stored.
*/

$smilereplacement = array("<img src=images/smiley.gif>",
 
"<img src=images/tongue.gif>""<img src=images/wink.gif>");

// replace the symbols in the message with the html & urls

$text str_replace($smilekey$smilereplacement$text);

// end of added code


   
?>


forgetting something??

in the last piece of the first script theres a bit with $usercomments = "<BR><BR><div align=\"left\" border=\"1\">". $usercomments. "<div><br>";
shouldn't the last <div> be a </div>???


last script

Howcome the last script double+ posts if you refresh the page more than once, is there anyway to stop that? also is there anyway to stop the un-used table from apearing until it is used?


Fixed

Oops! I fixed the </div> - thanks for pointing that out! As for the script printing an empty table. I am not sure where you are talking about. However, you can alway test variables to see if they are empty. So something like this would work.

<?php
//If not (empty) $variable (i.e. if it is not empty)
if(!$variable) {
    print 
'<table></table>';
}
?>


Another error? or just me?

Ok, after typing out the second script in SciTE and found errors in it once I put it to my server(the errors I made by typo).

I copyed and pasted the script and put it in a new SciTE page(I find it easyer to search for typos/errors that way)once done I saved the copyed script and ran that on my server aswell.

I used your script and found an error when typing in five lines into the textarea . What happens is it creates 4 tables including one empty/un-used table.

So.. the big question is... Is it just me or do you have the same error?

also, when i type something into the three boxes and submit it(when the file is empty) I get the text:
Your Message Has Been Added
File is empty.

It should have Your Message Has Been Added & the submited table should it not?

UPDATE: I have come to the conclusion that it IS return/enter making more tables to be added

Regards,
Vinnie

P.S Woah this is such a long post,
please do your best to help


Error..

Sigh..

Parse error: syntax error, unexpected T_VARIABLE in C:\Program Files\VertrigoServ\www\code2design\phplessons\chatscript.php on line 6


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