Jump to content

How To Create A Chat System Using Php And Ajax That Includes Private Sessions Between Users


dante3000

Recommended Posts

style3.csstesting.phpmakesend.phpstyle3.cssi really do hope to get a helpful answer. i've been working on a way to make a chatbox that allows private sessions between two users,one where only two users chat with the option of joining the general chatroom, i'm doing this without any xmpp,sockets etc, i'm just using files which would serve as logs, i'll explain the concept: a user has logged in, they are directed to the chat-page, where a list of their friends stored in a database is loaded to their right, this part is working fine:

 

//i've declared all the variables previously
//skip to the part that loads the names:
while($rowb=mysql_fetch_array($done))
{
$rafiki=$rowb['name'];
//show the names,when the user clicks on any of them, the name(variable $jina) of the user
//and the friend's name are sent to the function makefile()
echo "<a href='Javascript:makefile(".$jina.",".$rafiki.")'>"."$rafiki"."</a>"."<br/>";
}

 

when the user clicks on any name, they are sent to the javascript function, which takes both parameters, the user's name and the name of the friend, and then adds an extension at the end, to make a log file that would serve as the chat log between both of them:

 

function makefile(username,friendname)
{
//add file extension
var ext=".html";
//concatenate
var dash="-";
var full=username.concat(dash,friendname,dash,ext);
var str=friendname.concat(dash,username,dash,ext);

 

so each pair would have their own file, the variable full is sent to a script via ajax to make the process seamless, the script does a number of things: it first checks to see if a log file, that bears the data sent from the client side exists, either beginning with the user's name or the friend's name,if either file exists,it checks to see if any messages have been sent and writes them to the file, if neither file exists, it creates a new file,and prompts a user that a friend wants to start a chat, when the friend clicks on the user's name, the first condition will succeed, because a file would already have been made:

 

<?php
session_start();
$full=$_POST['full'];
//first, check to see if variations of the file already exist
//start by exploding the sent data
$result=explode("-",$full);
$usrnme=$result[0];
$frndnme=$result[1];
$ext=$result[2];
//make varied names for comparison
$vrdfull=array($result[1],$result[0],$result[2]);
$str=implode("-",$vrdfull);
$_SESSION['str']=$str;
$_SESSION['full']=$full;
//start actual comparison
if(file_exists($full)||file_exists($str))
{
//stuff to do if first file exists
if(file_exists($full))
{
//check to see if message has been sent
if (isset($_POST['message']))
{
$message=$_POST['message'];
//update existing file with message
$fp=fopen($full,'a');
fwrite($fp, "<div id=\"sent\">".$usrnme." :"." ".$message."<br/>"."</div>");
//close the file
fclose($fp);
}
}
else
//stuff to do if second file exists
{if(file_exists($str))
{
//check to see if message has been sent
if (isset($_POST['message']))
{
$message=$_POST['message'];
//update existing file with message
$fpp=fopen($str,'a');
fwrite($fpp, "<div id=\"sent\">".$usrname." :"." ".$message."<br/>"."</div>");
//close the file
fclose($fpp);
}
}
}
}
else
{
//create file, since neither files exist
$fhandel=fopen($full,'a');
//check if message has been sent
if(isset($_POST['message']))
{
$messssage=$_POST['message'];
fwrite($fhandel,"<div id=\"sent\">".$usrname." "." : ".$messssage."<br/>"."</div>");
}
fclose($fhandel);
//send msg to friend, incurring them to accept
$ext=".html";
$frrnme=$frndnme.$ext;
$fpp=fopen($frrnme,'a');
//prompt the user to initiate chat by opening file,by clicking on the name he/she would see
fwrite($fpp,"<div id=\"msg\">".$frndnme." wants to chat, click on their name to accept"."</div>");
fclose($fpp);
}
?>

 

i don't think this part has any problems, just posted it to help convey the idea across.here's the ajax that sends the string full to the script (i think it may be wrong):

 

$.ajax({
type:'POST',
url:'makesend.php',
data: {full:full},
//what to do if data was sent:
success: function(full){
$('#myResponse').html(full);[/font][/color]

[color=#000000][font=Arial, 'Liberation Sans', 'DejaVu Sans', sans-serif]}
});
return false;

 

no data is shown in the div "myresponse", so i think there's a problem here, i don't know what. the next thing would be to handle messages sent by the users,here's the form that would get their input:

 

<form name="message" action="">
<input name="message" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" onclick="send()" id="submitmsg" value="Send" />
</form>

 

and here's the function send() that sends data to the makesend.php file:

 

function send(){
var clientmsg = $("#usermsg").val();
$.post("makesend.php", {message: clientmsg});			
$("#usermsg").attr("value", "");
return false;
}

 

again, when i tested this and wrote a message, the page reloaded and no data was sent to the script! there's a problem here as well,i don't know what it is. moving on, after the file has been created and the user's begin interaction, it needs to be uploaded to a message area where the user can see it, here's the message area div:

remember that i'll need to load a file that exists, so before loading it to this area, i'll need to use php to see which version exists, either one with the user's name first or with the friend's name (either $full or $str):

$("#msgarea").html(
"<?php
//check to see if either file exists
if(file_exists($_SESSION['full'])||file_exists($_SESSION['str'])){
//check to see if the first file exists:
	 if(file_exists($_SESSION['full']))
{
$full=$_SESSION['full'];
$handlle = fopen($full, "r");
$contents = fread($handlle, filesize($full));
fclose($handlle);
//load it's contents to the division if it does
echo $contents;}
else
{
	 //if first file doesn't exist, load the second one:
$str=$_SESSION['str'];
	 //check to see if it exists before loading it
if(file_exists($str))
{
$handle = fopen($str, 'r');
$contents = fread($handle, filesize($str));
fclose($handle);
//load it to the division
echo $contents;
}
}
}
?>"
);

 

i think it's legal to do that, add php code to the innerHTML of an element, so this code would load whatever version of the file that exists. i get the file names from the session because this part of the code gets executed after data is sent to the makesend.php file, which starts a session and gives them ($_SESSION['full'] and $_SESSION['str']) values. this part that loads the file is the last piece of code within the function makefile(), first, the function obtains data from the user in form of the name they clicked, it sends them to a script (makesend.php) which creates the chat log file, after this, comes the last part, which loads the data onto the division "msgarea". next, i'd need to refresh/reload the created log file after a certain amount of time to show the messages sent by the users, i chose to use 2.5 seconds, this part is outside the function makefile(),i had to use php within the jquery to first check which file exists, i'd then use jquery in the php to reload and animate(auto-scroll) the existing one,this php is inside the 'javascript' tags:

 

<?php
//set up the conditions[/font][/color]
$full=$_SESSION['full'];
$str=$_SESSION['str'];
//check whether either file exists
if(file_exists($full)||file_exists($str))
{
//reload the first file if it exists
if(file_exists($full)){
//this is the jquery inside the php(which is also in javascript tags)
echo '<script type="text/javascript" src="jquery-1.8.0.min (1).js"></script>';
echo '<script type="text/javascript">';
echo
'function loadLog(){	
var oldscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
$.ajax({
 url: <?php session_start(); echo $_SESSION[\'full\']?>,
 cache: false,
 success: function(html){	
	 $("#msgarea").html(html); //Insert chat log into the #msgarea div			
	 var newscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
	 if(newscrollHeight > oldscrollHeight){
		 $("#msgarea").animate({ scrollTop: newscrollHeight }, \'normal\'); //Autoscroll to bottom of div
	 }			
 },
});
}
setInterval (loadLog, 2500); //Reload file every 2.5 seconds';
}
else{
//this will reload the second file since the first doesn't exist:
echo
'function lloadLog(){	
var oldscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
$.ajax({
 url: <?php session_start(); echo $_SESSION[\'str\']?>,
 cache: false,
 success: function(html){	
	 $("#msgarea").html(html); //Insert chat log into the #msgarea div			
	 var newscrollHeight = $("#msgarea").attr("scrollHeight") - 20;
	 if(newscrollHeight > oldscrollHeight){
		 $("#msgarea").animate({ scrollTop: newscrollHeight }, \'normal\'); //Autoscroll to bottom of div
	 }			
 },
});
}
setInterval (lloadLog, 2500); //Reload file every 2.5 secsonds';
}
echo '</script>';
}
?>

 

and i think that's it, the entire system, also, there's a problem with the logout call, here's the code, it's at the very end of the file: $("#exit").click(function(){ var exit = confirm("Are you sure you want to end the session?"); if(exit==true){window.location = 'testing.php?logout=true';}

}); here's the markup for it:

 

<p class="logout"><a id="exit" href="#">Exit Chat</a></p>

 

and at the top of the file, here's the part that checks whether it's set to true:

 

session_start();
//logout function
if(isset($_GET['logout']))
{
if(file_exists($_SESSION['full'])||file_exists($_SESSION['str']))
{
if(file_exists($_SESSION['full']))
{
$full=$_SESSION['full'];
$flogout=fopen($full,'a');
fwrite($flogout, $_SESSION['username']." has left the anichat!!! "."<br>");
fclose($flogout);
}
else
{
$str=$_SESSION['str'];
if(file_exists($str))
{
$flogoout=fopen($str,'a');
fwrite($flogoout, $_SESSION['username']." has left the chat "."<br>");
fclose($flogoout);
}
}
}
session_destroy();
header("Location:testing.php");//user redircect.
}

the user's page is not even refreshed so that the session is destroyed, it just refreshes and the session data is still present(this is because the login form isn't shown, it's supposed to be shown if the $_SESSION['name'] is empty). i know that this is a long question, but i am a beginner and i really need help with this, i think the main issues are with the ajax, but if you can spot anything else i will be very thankful, i kindly ask for a relevant answer that will help me implement this, if you would like me to post the entire code present in both testing.php and makesend.php,in a way that is not separated like the way i've done here to illustrate, please ask if it helps.i thank all you advanced programmers who go out of their way to help others, thanks in advance. i used phpmyadmin to set up the tables etc. i think that the ajax could be the problem any help will be highly appreciated, thanks in advance, i've attatched the relevant files.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.