Hi. This script has been extremely helpful. Thank you so much for posting it!
I'm currently integrating it as a chat window in a multicast streaming media client I'm working on. Here are some of the improvements I've made:
Fixed login bug
Fixed error where client would not close connection with database
Added more informative error dialogues
Increment identical usernames by adding a number to them
User SERVER_MSG added for broadcasting special output
Automatically drop users who have timed out
Quit message on client exit
There is so much that can be done with this. I've only just started.
I'm very new to php and working with mysql databases and would appreciate it if someone more experienced could offer some suggestions for optimizing the number of queries made by this script. I'm also interested in learning how to queue mysql queries to prevent congestion errors.
Here is my updated code:
ahkusers mysql table
Code:
CREATE TABLE `ahkchatusers` (
`userid` int(11) NOT NULL auto_increment,
`username` varchar(50) NOT NULL default '',
`loggedin` char(3) NOT NULL default '',
`ip` varchar(50) NOT NULL default '',
`lastping` timestamp NOT NULL default CURRENT_TIMESTAMP,
`lastmsg` int(11) NOT NULL default '0',
PRIMARY KEY (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
chat.php
Code:
<?php
/* Warning codes, put to errorlog
W001: Username already in use
*/
$event = $_GET['event'];
$msg = $_GET['msg'];
$username = $_GET['loggedusername'];
$loggedusername = $_GET['loggedusername'];
if ($db = mysql_connect('**server**', '**username**', '**password**')) {
mysql_select_db('**database**', $db);
//echo 'Connected to the database.';
} else {
die('Could not connect: ' . mysql_error());
}
if ($event == 'chat') {
$sql_events = mysql_query("SELECT * FROM ahkchatusers where username='$loggedusername' and loggedin='yes'") or die (mysql_error());
while ($row = mysql_fetch_array($sql_events)) {
$lastmsg = $row["lastmsg"];
}
$sql_events2 = mysql_query("SELECT * FROM ahkchatchat where msgid>$lastmsg order by msgid desc") or die (mysql_error());
while ($row = mysql_fetch_array($sql_events2)) {
$username = $row["username"];
$date = $row["date"];
$msg = $row["msg"];
$msgid = $row["msgid"];
$hour = date("g:i a", strtotime($date));
if ($username <> "SERVER_MSG") {
echo '[' . $hour . ']« ' . $username . ' » ' . $msg . '&()';
}
else {
echo '[' . $hour . '] ' . $msg . '&()';
}
}
if ($msgid != '') {
$query = "UPDATE ahkchatusers SET lastmsg='$msgid' where username='$loggedusername' and loggedin='yes'";
mysql_query($query) or die("Could not connect: " . mysql_error());
}
}
if ($event == 'login') {
$sql_events3 = mysql_query("SELECT * FROM ahkchatusers where username='$username' limit 1") or die (mysql_error());
while ($row = mysql_fetch_array($sql_events3)) {
$loggedin = $row["loggedin"];
}
if ($loggedin == 'yes') {
echo "Warning: W001";
}
if ($loggedin == 'no') {
$ip = GetHostByName($REMOTE_ADDR);
$query2 = "UPDATE ahkchatusers SET loggedin='yes', ip='$ip' where username='$username'";
mysql_query($query2) or die("Could not connect: " . mysql_error());
echo "success";
}
if ($loggedin == '') {
$ip = GetHostByName($REMOTE_ADDR);
$query3 = "INSERT INTO ahkchatusers (username, loggedin, ip) VALUES ('$username', 'yes', '$ip')";
mysql_query($query3) or die('Error, insert query failed');
echo "success";
}
$result = mysql_query("SELECT * FROM ahkchatchat") or die (mysql_error());
$num_rows = mysql_num_rows($result);
$query4 = "UPDATE ahkchatusers SET lastmsg='$num_rows'";
mysql_query($query4) or die("Could not connect: " . mysql_error());
}
if ($event == 'logout') {
$query5 = "UPDATE ahkchatusers SET loggedin='no' where username='$username'";
mysql_query($query5) or die("Could not connect: " . mysql_error());
}
if ($event == 'sendtext') {
$query6 = "INSERT INTO ahkchatchat (username, msg) VALUES ('$username', '$msg')";
mysql_query($query6) or die('Error, insert query failed');
}
if ($event == 'userlist') {
$sql_events4 = mysql_query("SELECT * FROM ahkchatusers where loggedin='yes'") or die (mysql_error());
while ($row = mysql_fetch_array($sql_events4)) {
$username = $row["username"];
echo $username;
echo ' &()';
}
}
if ($event == 'ping') {
mysql_query("UPDATE ahkchatusers SET lastping=CURRENT_TIMESTAMP WHERE username='$username'") or die('Error, insert query failed');
}
if ($event == 'whoisactive') {
$query_myping = mysql_query("SELECT * FROM ahkchatusers where username='$username' limit 1") or die (mysql_error());
while ($row = mysql_fetch_array($query_myping)) {
$myping = $row["lastping"];
}
$query_username = mysql_query("SELECT * FROM ahkchatusers where loggedin='yes'") or die (mysql_error());
while ($row = mysql_fetch_array($query_username)) {
$username = $row["username"];
$query_userping = mysql_query("SELECT * FROM ahkchatusers where username='$username' limit 1") or die (mysql_error());
while ($row = mysql_fetch_array($query_userping)) {
$theirping = $row["lastping"];
}
$mytime=strtotime($myping);
$theirtime=strtotime($theirping);
$diff = $mytime-$theirtime;
if ($diff >= 30) {
mysql_query("UPDATE ahkchatusers SET loggedin='no' where username='$username'") or die('Error, insert query failed');
mysql_query("INSERT INTO ahkchatchat (username, msg) VALUES ('SERVER_MSG', 'Quits: $username (Connection timed out)')") or die('Error, insert query failed');
}
}
}
//username ='$username'
//$query5 = "UPDATE ahkchatusers SET loggedin='no' where username='$username'";
//UPDATE ahkchatusers SET lastping = CURRENT_TIMESTAMP WHERE userid =2 LIMIT 1 ;
//2006-11-12 20:21:11
mysql_close($db);
?>
ahk script
Code:
#Persistent
#SingleInstance off
start:
Gui, Add, Edit, x76 y10 w100 h20 vusername ,
Gui, Add, Text, x6 y10 w70 h20 , User Name:
Gui, Add, Button, x43 y40 w100 h30 glogin +default, Login
Gui, Show, h83 w188, Login
Return
login:
gui submit
gui destroy
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=login&loggedusername=%username%, %A_Temp%\login.txt
FileReadLine, loginresult, %A_Temp%\login.txt, 1
loginresult = %loginresult%
;Check for warnings
IfInString, loginresult, Warning: W001
{
uNum = 1
loop
{
username = %username%%uNum%
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=login&loggedusername=%username%, %A_Temp%\login.txt
FileReadLine, loginresult, %A_Temp%\login.txt, 1
loginresult = %loginresult%
IfNotInString, loginresult, Warning: W001
{
break
}
StringTrimRight username,username,1
uNum := uNum + 1
}
}
if loginresult <> success
{
FileRead, loginresult, %A_Temp%\login.txt
;Check for errors
IfInString, loginresult, Could not connect
{
msgbox Could not connect to server.
goto start
}
IfInString, loginresult, Too many connections
{
msgbox Login failed: Too many connections
goto start
}
msgbox,,Warning, There was a problem logging in. Please try again.
goto start
}
if loginresult = success
{
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=userlist, %A_Temp%\userlist.txt
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=chat&loggedusername=%username%, %A_Temp%\chat.txt
FileReadLine, userlist, %A_Temp%\userlist.txt, 1
StringReplace, userlist, userlist, &(), `n, 1
FileReadLine, chat, %A_Temp%\chat.txt, 1
StringReplace, chat, chat, &(), `n, 1
SetTimer, updatechat, 5000
SetTimer, whoisactive, 30000
goto displaychat
}
displaychat:
Gui, Add, Edit, x6 y310 w350 h20 vsendtext,
Gui, Add, Button, x366 y310 w100 h20 gsend +default, Send
Gui, font,, Arial
Gui, Add, Edit, x6 y10 w350 h290 +readonly vchat,
Gui, Add, Edit, x366 y10 w100 h290 +readonly vuserlist, %userlist%
Gui, Show, h342 w477, AHK Chat
Return
send:
gui submit, nohide
SetTimer, updatechat, off
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=sendtext&loggedusername=%username%&msg=%sendtext%, %A_Temp%\sendtxt.txt
gosub, updatechat
guicontrol,, sendtext,
SetTimer, updatechat, on
return
updatechat:
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=ping&loggedusername=%username%, %A_Temp%\tmp.txt
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=chat&loggedusername=%username%, %A_Temp%\chat.txt
FileReadLine, chatnew, %A_Temp%\chat.txt, 1
if chatnew <> ''
{
chat = %chat%%chatnew%
}
StringReplace, chat, chat, &(),`n, 1
guiControl,, chat, %chat%
chatnew =
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=userlist, %A_Temp%\userlist.txt
FileReadLine, userlist, %A_Temp%\userlist.txt, 1
StringReplace, userlist, userlist, &(), `n, 1
guicontrol,, userlist, %userlist%
return
whoisactive:
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=whoisactive&loggedusername=%username%, %A_Temp%\tmp.txt
return
GuiClose:
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=sendtext&loggedusername=SERVER_MSG&msg=Quits: %username% (User left), %A_Temp%\sendtxt.txt
URLDownloadToFile, http://localhost/ahkchat/chat.php?event=logout&loggedusername=%username%, %A_Temp%\logout.txt
FileDelete, %A_Temp%\tmp.txt
FileDelete, %A_Temp%\logout.txt
FileDelete, %A_Temp%\userlist.txt
FileDelete, %A_Temp%\chat.txt
FileDelete, %A_Temp%\login.txt
FileDelete, %A_Temp%\send.txt
ExitApp