PHP - My Own Realtime Chat Script
Hello everyone, im new here. so to begin with i wanted to ask you about my realtime chat script im creating. You can check it out here http://madnet.us.lt/chat.php. Please! i repeat PLEASE, dont use any tags or sumtin in input fields, the chat is still unsafe! It only works in some versions of Opera, Mozila(best) and i think it should work on Chrome, but god no ,dont use IE This is my first
project i created so dont judge me if the code sounds stupid to you:D I made this using php/html/jquery and css . My first problem is that i used timeout function for chat div refresh, i dont think its the best way to get data from mysql, couse if like 500 or more people will get refreshes every 1 second, i think the server would crash, maybe you could get me through this with an alternative. Another problem is as i mentioned before that this chat is not capable with all explorers people use today. Third problem is that i cant figure it out how to make the public and clan buttons work (i only manage to get one of them work, if i make another one work then they conflict(nevermind you will see in the code)). I got a lot of more questions about security and stuff. but for now i would like to get the answers how to fix these things. Now il share you the code. I will accept all you advices so be free to say anything you think would be better for my real time chat. Im attaching the chat files.You will find the mysql tables in the zip Many thanks! [attachment deleted by admin] Similar TutorialsCan anyone suggest some good php Script(or Weburl) to do chat part in my php system please... Thanks in advance Hi, I was trying to build a chat room and tried the code given he http://www.codingmix.com/2010/12/privat ... mment-form but when i try to go to chat , sending is disabled and I cant chat Can anyone help? Also I want to create a room for chat like: based on a topic some more features like Adding a topic........and while chat choose the category like speaking for the topic, against or neutral and with option to post a point while chatting please help pooja_dubey12 Forum Newbie Posts: 3 Joined: Fri Jul 03, 2009 8:29 am This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=342897.0 Hi I'm currently having a problem with my chat script each time I'm trying to insert " or brackets etc... I get the error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/u471530368/public_html/chat/page.php on line 201
Here is the lines at line 201
// check to see if a duplicate exists $sql = "SELECT * FROM StringyChat WHERE StringyChat_ip=\"$ip\" AND StringyChat_message=\"$msg\" AND StringyChat_time>($post_time - 30 )"; $result = mysql_query($sql); $myrow = mysql_fetch_array($result); if($myrow["StringyChat_message"] == "") { // Checks if record not matching in db // Save the record $sql = "INSERT INTO StringyChat (StringyChat_ip,StringyChat_name,StringyChat_message,StringyChat_time) VALUES (\"$ip\",\"$name\",\"$msg\",$post_time)"; $result = mysql_query($sql); $theTo = $email_notification_to; $theSubject = "New StringyChat post at ".$domain_installed; $theMessage = "A new StringyChat post has been made.\n\n"; $theMessage .= $name . "\n"; $theMessage .= date("H:i - d/m/y", $post_time) . "\n"; $theMessage .= $message_emailable . "\n\n"; $theMessage .= "Visit ".$domain_installed." to view StringyChat and much more!"; $theHeaders = "From: StringyChat at ".$domain_installed." <".$email_notification_to.">\r\n"; mail($theTo,$theSubject,$theMessage,$theHeaders); } else { echo "<span style='color:#10ce59'>Duplicate post detected!</span><p>"; } } else { echo "<span style='color:#10ce59'>You can't send blanks!</span><br><br>"; }My full script is <?php define('TIMEZONE', 'Africa/Harare'); date_default_timezone_set(TIMEZONE); ?> <html><br> <b><u>Chat Beta:</u></b> <span style="color:#ff0000"><br>Errors may apply please send feedback with contact us regarding problems!</span> <br><a href="page.php">Reload</a> </html> <? // database connection info $conn = mysql_connect('*******','********','*****') or trigger_error("SQL", E_USER_ERROR); $db = mysql_select_db('*******',$conn) or trigger_error("SQL", E_USER_ERROR); // find out how many rows are in the table $sql = "SELECT COUNT(*) FROM StringyChat"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($result); $numrows = $r[0]; // number of rows to show per page $rowsperpage = 20; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; /* * StringyChat * * Please refer to readme.txt supplied with the StringyChat distribution for information on * installing and configuring. * */ define('TIMEZONE', 'Africa/Harare'); date_default_timezone_set(TIMEZONE); include("chat_code_header.php"); $result = mysql_query("SELECT * FROM ".$ConfigTable, $db); $myrow = mysql_fetch_array($result); $domain_installed = $myrow["domain_installed"]; // The domain StringyChat is installed on $install_url = $myrow["install_url"]; // URL to install dir of StringyChat $name_size = $myrow["name_size"]; // Maximum size of the name $message_size = $myrow["message_size"]; // Maximum message size. Do not exceed 250 as this is the database limit. $line_length = $myrow["line_length"]; // Maximum length of words in a line. Anything above this value will be split. $ShowPostNum = $myrow["show_posts"]; // The number of historic posts to load and display. $email_notification = $myrow["email_notification"]; // Send email to administrator when new posts are made. 0 = No, 1 = Yes $email_notification_to = $myrow["email_notification_to"]; // The email address to send notifications to if ($_SERVER['REQUEST_METHOD'] == "POST" && !empty($_POST['StringyChat_name'])) { $StringyChat_name = $_POST['StringyChat_name']; $StringyChat_message = $_POST['StringyChat_message']; } ?> <div id="StringyChat"> <? // Check if visitor's IP is banned. If so, do not display the form, // show a banned IP message instead. $name = $_SERVER["HTTP_X_MXIT_NICK"]; if(!isset($name)) { $name = "SYSOP"; } $ip = $_SERVER["REMOTE_ADDR"]; $sql = "SELECT * FROM StringyChat_IPBan WHERE ip=\"$ip\""; $result = mysql_query($sql); $myrow = mysql_fetch_array($result); if($myrow["ip"] == "") { // Checks if IP not found in banned list ?> <html><form name="StringyChat_form" method="POST" action="<? echo $_SERVER['REQUEST_URI']; ?>"> <input type="hidden" name="StringyChat_name" class="StringyChatFrm" value="<?php echo $name ?>" size="20"> <textarea name="StringyChat_message" class="StringyChatFrm" cols="20" rows="1"></textarea> <br> <input name="StringyChat_submit" class="StringyChatFrm" type="submit" value="Post Message"> </form> </html> <? } else { echo "<span style='color:#10ce59'><u>Dear User, you have been banned from the Chat due to not following the rules. You will need to come back regularly to see if you were unbanned. Until then, goodbye!</u></span>"; } // Should we try to create a post? if (isset($StringyChat_name) && isset($StringyChat_message)) { // Remove whitespaces and slashes. $name = trim(stripslashes($StringyChat_name)); $message = trim(stripslashes($StringyChat_message)); // Check name and message have been entered. if (strlen($name) > 0 && strlen($message) > 0) { // Limit the size of the fields as per variable defnitions. if (strlen($name) > $name_size) { $name = substr($name, 0, $name_size); } if (strlen($message) > $message_size) { $message = substr($message, 0, $message_size); } // Remove new lines from name. $name = str_replace("\n", " ", $name); // Stripping out \r's so email formattnig appears correctly. $message = str_replace("\r", "", $message); // Create an email-friendly version of the message. $message_emailable = str_replace("<br>", "\n", $message); $result_wordswap = mysql_query("SELECT * FROM ".$WordBanTable,$db); while ($myrow_wordswap = mysql_fetch_array($result_wordswap)) { $the_word = $myrow_wordswap["word"]; $message_emailable = ereg_replace($the_word, "!*#$%",$message_emailable); } // Replace the new lines with encoded line breaks for HTML (thanks milahu). $message = str_replace("\n", "c#lb", $message); // Use HTML encoding on ame and message so database doesn't misinterpret data. $name = htmlentities($name); $message = htmlentities($message, ENT_COMPAT); // IP address of submitter and time of post. $ip = $_SERVER["REMOTE_ADDR"]; $name = $_SERVER["HTTP_X_MXIT_NICK"]; $msg = $_POST['StringyChat_message']; $post_time = date("U"); $mxitid = $_SERVER["HTTP_X_MXIT_LOGIN"]; if(!isset($mxitid)) { $mxitid = "DEFAULT"; } if(!isset($name)) { $name = "SYSOP"; } // check to see if a duplicate exists $sql = "SELECT * FROM StringyChat WHERE StringyChat_ip=\"$ip\" AND StringyChat_message=\"$msg\" AND StringyChat_time>($post_time - 30 )"; $result = mysql_query($sql); $myrow = mysql_fetch_array($result); if($myrow["StringyChat_message"] == "") { // Checks if record not matching in db // Save the record $sql = "INSERT INTO StringyChat (StringyChat_ip,StringyChat_name,StringyChat_message,StringyChat_time) VALUES (\"$ip\",\"$name\",\"$msg\",$post_time)"; $result = mysql_query($sql); $theTo = $email_notification_to; $theSubject = "New StringyChat post at ".$domain_installed; $theMessage = "A new StringyChat post has been made.\n\n"; $theMessage .= $name . "\n"; $theMessage .= date("H:i - d/m/y", $post_time) . "\n"; $theMessage .= $message_emailable . "\n\n"; $theMessage .= "Visit ".$domain_installed." to view StringyChat and much more!"; $theHeaders = "From: StringyChat at ".$domain_installed." <".$email_notification_to.">\r\n"; mail($theTo,$theSubject,$theMessage,$theHeaders); } else { echo "<span style='color:#10ce59'>Duplicate post detected!</span><p>"; } } else { echo "<span style='color:#10ce59'>You can't send blanks!</span><br><br>"; } unset($_POST["StringyChat_name"]); unset($_POST["StringyChat_message"]); unset($StringyChat_ip); unset($StringyChat_name); unset($StringyChat_message); unset($StringyChat_time); unset($mxit_id); } // get the info from the db $sql = "SELECT StringyChat_time, StringyChat_name, StringyChat_message FROM StringyChat ORDER BY id DESC LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); function filterBadWords($str) { $result1 = mysql_query("SELECT word FROM StringyChat_WordBan") or die(mysql_error()); $replacements = ":-x"; while($row = mysql_fetch_assoc($result1)) { $str = eregi_replace($row['word'], str_repeat(':-x', strlen($row['word'])), $str); } return $str; } // while there are rows to be fetched... while ($list = mysql_fetch_assoc($result)) //while (($pmsg = $list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message']) { // echo data //echo ($pmsg = ($list['StringyChat_message'] == $bwords) ? ":-x" : $list['StringyChat_message']) $admin = array('cobusbo','Admin+TT'); if (in_array($list['StringyChat_name'], $admin)) { print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] ) . ') ' . '</span>' . '<span style="color:red">' . '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '</span>' . '<br />' . '<p>'; } else { print '<span style="color:#828282">' . '(' . date( 'D H:i:s', $list['StringyChat_time'] ) . ') ' . '</span>' . '<b>' . $list['StringyChat_name'] . '</b>' . ' : ' . filterBadWords($list['StringyChat_message']) . '<br />' . '<p>'; } } // Load up the last few posts. The number to load is defined by the "ShowPostNum" variable. $result = mysql_query("SELECT * FROM ".$dbTable." ORDER BY StringyChat_time DESC LIMIT " . $ShowPostNum,$db); include("sort_widths.php"); while ($myrow = mysql_fetch_array($result)) { $msg = $myrow["StringyChat_message"]; // Convert the encoded line break into an actual <br> tag (thanks milahu) $msg = str_replace("c#lb", "<br>", $msg); // Convert the encoded image tag into a html tag $msg = eregi_replace("im#([a-z]{3})", "<img src=\"http://".$install_url."images/\\1.gif\" alt=\"emoticon\">",$msg); // split the lines $msg = htmlwrap($msg, $line_length); $result_wordswap = mysql_query("SELECT * FROM ".$WordBanTable,$db); while ($myrow_wordswap = mysql_fetch_array($result_wordswap)) { $the_word = $myrow_wordswap["word"]; $msg = ereg_replace($the_word, ":-x",$msg); } } ?> <? // end while /****** build the pagination links ******/ // range of num links to show $range = 3; // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [<b>$x</b>] "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> "; // echo forward link for lastpage echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> "; } // end if /****** end build pagination links ******/ ?><br> <html> <span style="color:grey"><i>Type Your Message NOW!</i></span> <p><a href="page.php">Reload</a> | <a href="http://tt.2fh.co">Home</a><br></html>Any help please... If I send normal messages I don't get any errors... i am new with web socket
and in same time
I try to make server and client communication for soccer manager application, and for this purpose, i need to create closed "chat rooms" or "games" where two users can watch (read game event) and menage (create) game event (make substitution, formation ... or if you want, to send message to server, that they make changes in formation)
this game (room) mast bi secret, and only this two player can use this game for "read" and "write" events in game
for example: Game no: 200001 between user A and user B in 14.05.
when User A, and User B click on game no. 200001 they can read and write game event.
PS: for now, i create basic chat aplication with PHP, jQuery and webSocket and in this app, all user see wath all other user do (public chat) and i want to make secret chat for specific user (already automate subscribed from server) All work with no problem (i work on this example http://www.sanwebe.c...ket-php-socket)
How i can create chat room(s) and subscribe user to specific chat room?
Thanks
Edited by laponac84, 30 November 2014 - 09:09 AM. How can i make code which can do something when time is 00:00 ? Is that possible in php, and if not any suggestions? Hi all im trying to build a chat like chathotel.http://chathotel.nl can someone help me out what the best way is to start ? I know php just trying to get it like this doesn’t get me on a start thanks would be great Edited May 29, 2019 by requinixunlinking Hi Guys Somehow I can't make this chat work... maybe you've got an idea what the problem is? main.php <?php session_start(); ?> <html> <head> <title>Chat</title> <script language="JavaScript"> msg = new Array(); function showchat() { for (i = 0; i < msg.length; i++) { show.document.write(msg[i]; show.document.write("<br />"); } show.document.write("<a name='end'></a>"); } </script> </head> <frameset rows="0,*,45" border="0"> <frame name="main" src="main.php"> <frame name="show" src="show.php"> <frame name="send" src="send.php" scrolling="no"> </frameset> </html> <?php session_start(); $time = $_SESSION['time']; if (!isset($time)) $time = 0; $hdlDB = mysql_connect('localhost', 'root', ''); $strSQL = "SELECT * FROM chat WHERE time > '$curTime'"; $dhlRS = mysql_db_query('chat', $strSQL, $hdlDB); while ($arrRS = mysql_fetch_assoc($hdlRS)) { $arrMsg[] = '<b>' . $arrRS['sender'] . '</b>: ' . $arrRS['data']; $time = max($arrRS['time'], $time); } session_register('time'); ?> <html> <head> <title>Chat</title> <script language="JavaScript"> <?php if (is_array($arrMsg)) { $i = 0; foreach($arrMsg as $strLine) { echo "top.msg[$i] = '$strLine';\n"; $I++; } } ?> top.show.location.reload(); </script> </head> <body onload="window.setInterval('location.reload()', 4000)"> </body> </html> send.php <?php session_start(); if (!isset($time)) $time = 0; if (strlen($_POST['newmsg'] > 2) { $hdlDB = mysql_connect('localhost', 'root'; ''); $curTime = time(); $strSQL = "INSERT INTO chat (time, data, sender) VALUES ('$curTime', $newmsg', '$sender')"; mysql_db_query('chat', $strSQL, $hdlDB); session_register('time'); } /* end if */ ?> <html> <head> <title>Chat</title> <script language="JavaScript"> <?php if (is_array($arrMsg)) { foreach($arrMsg as $strLine) echo "top.msg[top.msg.length]=\"$strLine\""; } ?> top.show.location.reload(); </script> </head> <body bgcolor="white"> <form action="<?php echo $PHP_SELF; ?>" method="post"> <select name="sender" size="1"> <option value="Admin" <?php $sender == 'Admin' ? print 'selected' : print ''; ?>>Admin <option value="Client" <?php $sender == 'Client' ? print 'selected' : print ''; ?>>Client </select> 's Beitrag: <input type="Text" name="newmsg" size="40"> <input type="Submit" value="Send"> </form> </body> </html> show.php <html> <head> <title>Chat</title> </head> <body> <script language="JavaScript"> top.showchat(); </script> </body> </html> Database (chat) CREATE TABLE chat ( id bigint(20) NOT NULL auto_increment, time varchar(10) NOT NULL, data text, sender varchar(32) DEFAULT '1' NOT NULL, PRIMARY KEY (id), KEY id (id) ); cheers, ozzo Hi All... I am facing some problem while coding chat system.....my problem is that whenever i refresh the chat page the last message stored in the url by the current user displays again....its showing messages from the other users also but its keep on repeating the messages of the current user logged in,in the browser.....i am using post for all....do i need to try something else or any new way etc....if anybody have suggestions and solutions for the above mentioned problem then please do help me out...thank you... I bought script for live chat support but i want something more. Now you can login with admin role and operator role, but what i want is to add user role so when user login in app he can see online operators and chat with them. It is open source so there is no legal issue..
So if anyone wants to help me i will send script on your email and try to solve this..
Thanks,Ivan
Hi, I need to develop a module called chat with doctor. User can able to chat with the doctor for that he has to pay some amount to website. Say example user got purchase the Package worth : 2$ =>5min. After 5 min chat will be closed , timer should be shown while chatting. How can we do this? Hi, I'm trying to make an area where people can post stuff, status updates etc... I have a small layout done, but something has confused me. I'm trying to get it so when somebody is logged in, and posts something in the chat area, it displays: [Name] [Comment] I know how to read from the database, but for some reason, when I press the 'submit' button, the text in the 'comment' box isn't inserting into my 'comment' column in my database... But I want it so it inserts in the users column. Is this possible? Code: [Select] <?php if($submit) { $comment = $_POST['comment']; $submit = $_POST['submit']; $connect = mysql_connect("****","****","****") or die("Could not connect to database."); mysql_select_db("****") or die ("Could not find database!"); $query("INSERT INTO login ('comment') VALUES('$comment')"); $result = mysql_query($query) or die(mysql_error()); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form method="POST"> Comment: <input type="text" name="comment" /><br /> <input type="submit" name="submit" value="Submit" /><br /> </form> </body> </html> Hi i would like a simple chat page on my site for my members. i already have a site login database and want to know how i can let people chat and have their names entered with thier message without them having to login in to something else or typing their name with each message, for example - tom says: hello We want to add a chat feature in PHP for a social site can somebody suggest a good solution, a script maybe, where registered users when online can chat with other registered members in the friend list This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=316029.0 Below is a peice of code for my in game chat system and it works okay, but i would like a few things and i'm not sure of how to go about it. 1. the most recent post to be on top i beleive i might be able to do that with the time stamp i have. 2. when people post a comment for the line spaces to show up? (simple but im not sure how) 3. when it's a set user ie = playerx the font colour to be different. if anyone could help i'd be thankful. Code: [Select] <?php if ($sc == "") { diver ('Battle Of Species Global Game Talk'); $sql3 = "UPDATE users SET gamechat=0 where id=$userid"; mysql_query($sql3); echo '<center><BR>[<a href="index.php?cmd=chat&sc=chatadd">Add Post</a>]</center><BR><BR>'; $sql = "SELECT id FROM comm2 WHERE parent=0 ORDER BY `time` DESC"; $r = mysql_query($sql); while ($row = mysql_fetch_row($r)) { echo '<table border="0"><tr><td>'; showMessage($row[0], 0,$b); echo '</td></tr></table><BR><BR>'; } }else if ($sc =="chatadd") { diver ('Enter Your Post Below'); echo '<center>'; echo '<form method="post" action="index.php?cmd=chat&sc=chatadd2">'; echo '<input type="hidden" name="inPar" value="'.$inPar.'">'; echo '<textarea rows="10" cols="45" name="inText" style="'.$boxStyle.'"></textarea><BR><BR><input type="submit" value="Post">'; echo '</form></center>'; }else if ($sc == "chatadd2") { diver ("Message Posted"); $inText = clean($inText); $sql = sprintf("INSERT INTO comm2 (author,parent,time,post) VALUES ('%s','%s','".time()."','%s')", mysql_real_escape_string($userid), mysql_real_escape_string($inPar), mysql_real_escape_string($inText)); mysql_query($sql); $sql2 = "UPDATE users SET gamechat=1"; mysql_query($sql2); echo '<BR><BR><center>You message has been posted!<BR>[<a href="index.php?cmd=chat">Back to Game Chat</a>]'; } function showMessage($m, $l, $b) { global $prefDate; echo '<table border="0" style="font-famile: Verdana; font-size: 12px" cellpadding="4"><tr>'; for ($i = 0; $i < $l; $i++) { echo '<td> </td>'; } echo '<td>'; $sql = "SELECT `post`,`author`,`id`,`time` FROM `comm2` WHERE `id`='{$m}'"; $r = mysql_query($sql); $row = mysql_fetch_row($r); $row[0] = '<B>'.getvalue($row[1],'handle').'</B><BR>'. $row[0]; $row[0] .= '<BR>[<a href="index.php?cmd=chat&sc=chatadd&inPar='.$row[2].'">Reply</a>] [Posted: '. date($prefDate,$row[3]) .']'; echo str_replace(' ','<BR>',$row[0]); echo '</td></tr></table>'; $sql = "SELECT id FROM comm2 WHERE parent={$m} ORDER BY time DESC"; $r = mysql_query($sql); while ($row = mysql_fetch_row($r)) { showMessage($row[0], $l + 1, $b); } } [code] I need free php chat module or script. Please tell me any known or good script. thanks I am not sure how I should go about doing this. I have a server that has a chat server on it, people register an account and then have access to this chat server from their application. To initially connect to it, they need a game id and game stamp (kind of like a username/password for the game). I don't want chats from one application to display in another users application. When I created this chat server it was for another purpose, and could only support about 64,510 different chats since each chat ran on its own port. For my current purpose it is a little different some applications can have 1 - 10 chats going at once per user using the application. Say their is 100 people using the application and each is using 5 - 10 different chat windows. With 100 users on at the same time all chatting, that can get up to 1,000 different ports being used. I don't want that, because say there are 100 applications also using chat, that is about 100,000 different ports, and I am pretty sure you cant have 100,000 ports. So! I need a way to make a chat server, any ideas on how I could do this with my php? need more information? please ask! My database name is cute and in cute database contain chatmessages and ipbans tables in which chatmessages contains id(auto increment), name, IP,postime and message and here is the form2.php coding form 2.php Code: [Select] <?php mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("cute") or die(mysql_error()); $message=$_POST['message']; $n=$_POST['username']; $name=$_POST['name']; if(isset($_POST['submit'])) //if submit button push has been detected { if(strlen($message)>1) { $message=strip_tags($message); $IP=$_SERVER["REMOTE_ADDR"]; //grabs poster's IP $checkforbanned="SELECT IP from ipbans where IP='$IP'"; $checkforbanned2=mysql_query($checkforbanned) or die("Could not check for banned IPS"); if(mysql_num_rows($checkforbanned2)>0) //IP is in the banned list { print "You IP is banned from posting."; } else { $thedate = date("U"); //grab date and time of the post $insertmessage="INSERT into chatmessages (name,IP,postime,message) values('$name','$IP','$thedate','$message')"; mysql_query($insertmessage) or die("Could not insert message"); } } } ?> <html> <head> <script type="text/javascript"> function addsmiley(code) { var pretext = document.smile.message.value; this.code = code; document.smile.message.value = pretext + code; } function a() { var x = document.smile.message.value; if(x=="") { alert("Please insert an message!"); return false; } } </script> <style type="text/css"> body{ background-color: #d8da3d } </style> </head> <body> <form name="smile" method="post" action="form2.php" onSubmit="return a()" > Your message:<br><textarea name='message' cols='40' rows='2'></textarea><br> <img src="smile.gif" alt=":)" onClick="addsmiley(':)')" style="cursor:pointer;border:0" /> <img src="blush.gif" alt=":)" onClick="addsmiley('*blush*')" style="cursor:pointer;border:0" /> <input type="hidden" name="name" value="<?php echo $n;?>"> <input type='submit' name='submit' value='Set Name' class='biasa' ></form> <br> <br> </body> </html> my problem is if the first chat message that i click submit button it would be appear name:message but when the second time submit it only appear the message but the name is blank(nothing and empty) This is my login.php Code: [Select] <?php mysql_connect("localhost","root") or die(mysql_error()); mysql_select_db("Regis") or die(mysql_error()); if (isset($_POST["sub"])) { $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); $_POST['pass'] = addslashes($_POST['pass']); } $usercheck = $_POST["username"]; $check = mysql_query("SELECT username FROM registration WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('Sorry, the username" ." ".$usercheck." ". "is already in use.')</SCRIPT>"); echo ("<SCRIPT LANGUAGE='JavaScript'>setTimeOut(window.location = 'registration.php',1)</script>"); } else if($_POST['username'] && $_POST['pass'] && $_POST['pass2'] ) { $insert = "INSERT INTO registration (username, password) VALUES ('".$_POST['username']."', '".$_POST['pass']."')"; $add_member = mysql_query($insert); echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('Registration had been succesfully added :)')</SCRIPT>"); } } ?> <html> <head> <script type="text/javascript"> function a() { var x = document.login.username.value; var y = document.login.pass.value; if(x==""&& y=="") { alert("Please insert all message!"); return false; } if(x=="") { alert("Please insert an username!"); return false; } if(y=="") { alert("Please insert an password!"); return false; } } </script> </head> <body> <table border="0"> <form name="login" method="post" action="form2.php" onsubmit="return a()"> <tr><td colspan=2><h1>Login</h1></td></tr> <tr><td>Username:</td> <td><input type="text" name="username" maxlength="40"></td></tr> <tr><td>Password:</td> <td><input type="password" name="pass" maxlength="50"></td></tr> <tr><td><input type="submit" name="submit" value="Register"></a></td> <td><input type="submit" name="submit" value="Login"></td></tr> </form> </body></html> So how to make when the second and next submit click button, it would appear name with message ?[/b] I've been trying to think of the best way to build a PHP based chat room. Obviously a push method would work the greatest but I have been unable to find any such techniques using PHP so this is the only alternative I can think of. When a user logs in to the chat, a file is created in a secure directory on the server for the user. This file will store messages to be sent to the user. Each time someone sends a message to the chat, the message is inserted into every user's file. Then, using AJAX, the user in chat will "reload" the chat every few seconds, which will simply access a PHP script that reads the file, sends it to the user, then truncates the file contents to zero. My concern is obviously the high frequency of server loads to access the chat file, but this is why I would try to minimize the server's effort for retrieving chat content and focus the efforts more on sending messages since this action is done less often. I'm looking for suggestions on what would be best to keep the system efficient... maybe some ideas of headers to send which may help with optimization. Thank you for your time. |