Get support from Xavier Media
It is currently Sun Dec 08, 2013 3:41 pm

All times are UTC




Post new topic Reply to topic  [ 5 posts ] 
Author Message
 Post subject: Lesson 19 - Reading External Files into PHP - Part 4
PostPosted: Tue Aug 08, 2006 9:09 pm 

Points:
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]
<?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;


?>
[/php]

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






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

?>
[/php]

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

}

?>
[/php]
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]
<?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>";
}
?>
[/php]




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

?>
[/php]
In English the if loop would read:

[php]
<?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.
}
?>
[/php]





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

?>
[/php]




6) Finally, We add some formatting to the comments so that they stay in a box. and print everything to the screen!
[php]
<?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;
/////////////////////////////////////////////////////////////////////////

?>
[/php]


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]
<?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($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><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>';


?>
[/php]


You can download both scripts here:
Lesson 19 Files


Report this post
Top
  
Reply with quote  
 Post subject: just one thing.
PostPosted: Sat Sep 09, 2006 9:44 pm 

Points:
I really feel stupid now cos i've done something like this b4, but, i've never thought of replacing the character to use as a seperator to secure it b4 writing the file $email = str_replace("|", "", $email);
without this, i've made things very very complicated for myelf for nothing. thanks a lot u're a genius! :!:

There is one thing i want you to know, getting a record if u like, of one submission by a fixed size is no good, cos som1 might post a long message. Too short or too long, it causes confusion. so what i suggest is to split the text into 2 arrays An array of arrays is the word for it.
The first array is loaded by splitting (exploding) the whole content of the file using "|\n|" for example; this means that we also need to change the way we write the information to the file as well:
[php]$content = "$name|$email|$msg|$date\n";[/php]
becomes for eg: [php]$content = "$name|$email|$msg|$date|\n|";[/php]

the loop changes
[php]while (!feof($handle)) {
$line = fgets($handle, 5096);[/php]
becomes: [php]$filecontent = fread($handle,filesize($file));
$line = explode("|\n|",$filecontent);
//notice that $line has become an array now, containing all the submissions separately
//the loop becomes a FOR loop:
for ($i=0;$i<count($line);$i++) {
@list($user_name, $user_email, $user_msg, $user_date) = explode("|", $line[$i]);
//...all the rest stays the same.
[/php]
i hope u get what i just wrote, cos it is very confusing to me even though i wrote it :roll: ...phew :cry: i confused myself.


Report this post
Top
  
Reply with quote  
 Post subject: Thanks
PostPosted: Sat Sep 09, 2006 11:08 pm 

Points:
Thanks, that is a good idea! :-D


So the changed Code would be something like:

[php]
<?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)) {


//
//// Changed Code
//


$filecontent = fread($handle,filesize($file));
$line = explode("|\n|",$filecontent);
/*
Notice that $line has become an array now, containing all the submissions separately
For example:
$line['3'] = "Bob|bob@aol.com|This is the message|Aug 24 2006";
(This is just an idea of what one array element of "$line" could
look like.)
*/


//The loop becomes a FOR loop:
for ($i=0;$i<count($line);$i++) {
@list($user_name, $user_email, $user_msg, $user_date) = explode("|", $line[$i]);

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>';
}

//
//// Changed Code
//

} 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>';


?>
[/php]


Report this post
Top
  
Reply with quote  
 Post subject: hmmm
PostPosted: Sun Sep 10, 2006 3:44 pm 

Points:
i just thought of something:
imagin if the user posts \n in any of the fields via post but the messages mainly, this means when u group them together, this will occur
myname|myemail|\n|mydate|\n|
can you see what i mean ? this is gonna get messed up during reading the file, so the best thing to do is like you did before, use str_replace if \n is posted on its own if any of the fields to avoid this.

Arivadechi :wink:


Report this post
Top
  
Reply with quote  
 Post subject: md5 and explode
PostPosted: Mon Sep 11, 2006 6:10 pm 

Points:
bugmenot wrote:
i just thought of something:
imagin if the user posts \n in any of the fields via post but the messages mainly, this means when u group them together, this will occur
myname|myemail|\n|mydate|\n|
can you see what i mean ? this is gonna get messed up during reading the file, so the best thing to do is like you did before, use str_replace if \n is posted on its own if any of the fields to avoid this.

Arivadechi :wink:



I just thought of how you can use a "separator" without the user knowing what it is, or accidentally using it and therefore messing-up your explode: use the md5() function!

for example:
[php]<?php
$separator = md5("something");
//now $separator is equal to something like ?1f3870be274f6c49b3e31a0c6728957f?
$lines = explode($separator,$filecontent);
?>[/php]

Then if you were still worried you could just change ?something? every month?


Report this post
Top
  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 5 posts ] 

All times are UTC


Who is online

Registered users: No registered users


You can post new topics in this forum
You can reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron

Portal » Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
[
SEO MOD © 2007 StarTrekGuide ]