to have a better chat, we need database. But in my example, I will skip the database and using text as my database. In bigger chat, you need field :
- name. Nama of user that type the chat.
- message. limit the message, is unwise to have message more than 200 words
- date. make this as auto date and time. In mysql I used timestamp.
- ip. which IP this chat comming from. better log it
- etc. You can add something to make sure your chat is safe.
Everyscript begin with config. We can put in one file or separated file. Even the tutorial is simple, better split the config away from main code.
<?php
$filechat="chat.txt";
$sep='[break]';
$time=2000;
?>
explaination:
filechat = the file i placce the chat
sep = separator
time = time to reload.. better add bigger in this?!?
okay now the main code.. beware this not include the css
<?phpinclude "config_chat.php";
if($_GET['t'])
{//============SHOW ME CHAT=====//
$f=file_get_contents($filechat);
$a=explode($sep,$f);
foreach($a as $val )
{
$val=trim($val);
if(!$val)continue;
$i=strpos( $val,"\n");
$s.="\n\t<div id='name'>".substr($val,0,$i)."</div>";
$s2=trim(substr($val,$i,strlen($val)));
$s.="\n\t<div id='msg'>".nl2br($s2)."</div>";
}
die($s);
}
?><script type="text/javascript" src="js/jquery.js"></script>
<script>
$(document).ready(function() {
setInterval(function() {
$('#message').load('?t='+ Math.random());
}, <?php echo $time;?>);
});
</script>
<div id="message"> your chat</div>
<hr>
<div id="submit">
</div>
explain:
if($_GET['t'])
{//============SHOW ME CHAT=====//
the code will be SHOW the message if there is variable t send using GET..
<script>
$(document).ready(function() {
setInterval(function() {
$('#message').load('?t='+ Math.random());
}, <?php echo $time;?>);
});
</script>
The script will be reload with the chat. Please beware, there are time that should be consider bigger or your server will be exhaust.
the chat will be reload into <div> for exact <div id='message' >
Next, we build chat.txt.. follow this example
adminnow run the code, you will see above chat.. next add
testing page[break]
Diana
Hey, where are you??
i'm waiting here[break]
Baryafter [break] and don't refresh.. We will see the chat is reload it self..
Hello World
next we will try to add input chat.
Tidak ada komentar:
Posting Komentar