PHP design chat room step by step

Source: Internet
Author: User
Tags chop

The chat room can run in a completely free way. You can enter the name at will, without a password, and do not save your chat status. The advantage is: freedom, which is very suitable for tourists! Another method is to register a chat room. Every person entering the chat room must enter his/her username and password before entering the room! Advantage: it fully reflects the personality and is very suitable for old friends. What do they say will not be maliciously occupied and used? My chat room uses the registration method!

Registration usually adopts two methods:

1. Register and chat
  
2. Automatic Registration

Modify your own information in it! I use 2nd methods !! The username of each new user will be automatically saved to the database. You must enter an accurate password for the next login!

The following is the judgment part! This program uses a Text Database!

// $ Useronline is the name of the online user's data file
// $ Useronlinelock is the identifier of the online user
// $ Register is the name of the registered data file
// $ Registerlock indicates the lock mark of the registered File
// $ Split is the Separator

// Enter the login Parameter
If ($ action = "enter ")
{
// Current time in seconds
$ Timecurrent = date ("U ");

// Lock the number of online users file to prevent simultaneous modification of the same file
While (file_exists ($ useronlinelock ))
{
If (! File_exists ($ useronlinelock ))
{
Break;
}
}

// Create a temporary file
Fclose (fopen ($ useronlinelock, "w "));

// Read the information of online users and registered users: Password, nickname, and update time
$ Useronline = file ($ useronline );
$ Register = file ($ register );

// Indicates whether the logon is successful.
$ Namesign = 0;

// Determine the user name. The password is incorrect. The user name cannot be blank, and cannot exceed 10 characters. The password cannot exceed 20 characters.
If ($ name = "") | (strlen ($ name)> 10) | (strlen ($ pass)> 20 ))
{
Print ("No nickname or long password ");
// Login Failed
$ Namesign = 1;
// Delete a temporary file
Unlink ($ useronlinelock );
}
Else
{
// Check whether someone has registered or the password is incorrect.
$ Foundsign = 0;
For ($ I = 0; $ I <count ($ register); $ I ++)
{
// Split
$ Tempregister = split ($ split, $ register [$ I], 99 );
// Find the registered user name
If ($ name = $ tempregister [0])
{
// The flag has been found.
$ Foundsign = 1;
// Is the password correct?
If ($ pass! = $ Tempregister [1])
Print ("wrong password! ");
// Login Failed
$ Namesign = 1;
Unlink ($ useronlinelock );
Break;
}
Else
{
// Old User Login successful
$ Namesign = 0;
Break;
}
}

}

// If this user name is not found, it will be automatically registered
If (! $ Foundsign)
{
// Save the user name and password
$ Handle = fopen ($ register, "");
Fputs ($ handle, "$ name $ split $ pass $ splitrn ");
Fclose ($ handle );
// New User Login successful
$ Namesign = 0;
}
}
}
If (! $ Namesign)
{
// Update the list of online users
$ Useronlinehandle = fopen ($ useronline, "w ");

// Judge whether it is already in, just refresh the page
$ Updatesign = 0;
For ($ I = 0; $ I <count ($ useronline); $ I ++)
{
$ Usertemp = split ($ split, chop ($ useronline [$ I]), 99 );
If ($ name = $ usertemp [0])
{
// Update the flag
$ Updatesign = 1;
Fputs ($ useronlinehandle, $ useronline [$ I]);
}
Else
{
Fputs ($ useronlinehandle, $ useronline [$ I]);
}
}
// If not, add it to it
If (! $ Updatesign)
Fputs ($ useronlinehandle, "$ name $ split $ level $ split $ pass $ split $ timecurren
Trn ");
Fclose ($ useronlinehandle );

// Remove the contraction
Unlink ($ useronlinelock );

// Login successful
}

At this point, the user verification has been completed, and the chat user has entered the chat room legally. What about the carrier name and password?


Login

1. Basic Elements of page Login

You can see the login form in my bamboo. Here we provide the most basic login form items.

(1) login form

<Form method = POST name = chatform action = chat/login. php? Action = enter onSubmit = "b1_submit (); return true;" target = "howtodo">

(A) The Chat form is named chatform. I use action = enter as the portal to enter the chat room. If this parameter is not provided, the login page is displayed.

(B) When submitting a form, call bw.submit () to create a chat window.

(C) The Target chat window is the howtodo window created by b1_submit ().

(2) Form Items

Nickname: <input type = text name = name size = 15 maxlength = "10">
Password: <input type = password name = pass size = 15 maxlength = "10">
<Input type = submit name = submit value = login style = "width: 100">
<Input type = reset name = reset value = add style = "width: 50">


(A) The maximum allowed length of each form item must be set. maxlength

(3) create a chat window js

<Script LANGUAGE = "javascript">
Function bmit submit (){
Chat = window. open (''," howtodo ", 'status = no, scrollbars = no, resizable = no ');

Chat. moveTo (0, 0 );
Chat. resizeTo (screen. availWidth, screen. availHeight );
Chat. outerWidth = screen. availWidth;
Chat. outerHeight = screen. availHeight;
}

This code first opens a howtodo window with no status bar and a scroll bar to adjust the size! Move to the upper left corner of the screen and zoom in to the allowed screen size.

Online users

Based on the number of online users in the Netease chat room, the current number of online users is displayed. The Code is as follows:
1. Create an array of online person lists during login and place them behind the body

<?
// Lock the number of online users file
While (file_exists ($ useronlinelock) {$ pppp ++ ;}
Fclose (fopen ($ useronlinelock, "w "));

// Read the online person list
$ Useronline = file ($ useronline );
Unlink ($ useronlinelock );

// Create an array list
Print ("document. writeln (" list = new Array (");
$ K = count ($ useronline );
If ($ k> 1)
{
For ($ I = 0; $ I <($ k-1); $ I ++)
{
$ Usercurrent = split ($ split, $ useronline [$ I], 99 );
// Name +,
Print ("'$ usercurrent [0]',");
}
$ I = $ K-1;
// Process the last name
$ Usercurrent = split ($ split, $ useronline [$ I], 99 );
Print ("'$ usercurrent [0]'");
}
// Array ends
Print (")"); n ");
?>

2. js showing the number of online users

Document. writeln ('[online users <font color = red>' + count + '</font>] <br> ');
Document. writeln ("[<a href =" javascript: parent. cs ('allow') "> all </
A>] <br> ");
Document. writeln ("<font class = 'p9 '> ");
Var j, name, club;
For (var I = 0; I <list. length; I = I + 1)
{
If (list [I]! = Null ){

// Display the name of each online person
Document. writeln ("<a href =" javascript: parent. cs ('"+ list [I] +"') "titl
E = '"+ list [I] +"'> "+ list [I] +" </a> <br> ");
}
}
This.r.doc ument. writeln ('</font>

3. Change the chat object

Function cs (name)
{
If(this.d.doc ument = null) return;
If (name = 'Everybody ')
{
This. d. add ('Everybody ');
This.d.doc ument. inputform. talkto. value = 'allow ';

// Change focus
This.d.doc ument. inputform. msg. focus ();
Return;
}
For (var I = 0; I <list. length; I = I + 1)
{
If (list [I] = name)
{

// Change the sent conversation object
This.d.doc ument. inputform. talkto. value = list [I];
This.d.doc ument. inputform. msg. focus ();
Return;
}
}

// Error
Alert ('the user has been offline or changed the nickname. ');
}

4. delete a user

Function del (str)
{
For (var I = 0; I <list. length; I = I + 1)
If (list [I] = str)
{
Delete list [I];
Count --;
}
}

5. Add a user

Function add (str1, str2)
{
Var l = list. length;
For (var I = 0; I <list. length; I = I + 1)

// If it is already in the array, return
If (list [I] = str1)
Return;

// Add a user
List [l] = str1;
Count ++;
}

6. Update the number of chat users and use the timer.

Var timerID = null;
Var timerRunning = false;

Function stop ()
{
// Stop
If (timerRunning) clearTimeout (timerID );
TimerRunning = false;
}
Function start ()
{
Stop ();
// Call the program to update the number of online users
Write1 ();
}

Function write1 ()
{
............
// Set the Update Time,
TimerID = setTimeout ("start ()", 30000 );
TimerRunning = true;
}

This method is relatively simple to display the number of online users. Of course, you can also use the method of reading the online person file to display the number of online users. However, it is troublesome to change the chat object.

Display

Currently, the www chat room basically adopts the frame method. You can also use frame or iframe to see what you like. My traditional frame method is used.

Print ("<frameset rows =" *, 110,0, 0,0 "border = 0> n ");
Print ("<frameset cols =" 660,118 "rows =" * "> n ");

// Displays the chat content on the main screen.
Print ("<frame name = u src = about: blank frameborder =" NO "noresize> n ");


// Number of online users Screen
Print ("<frame name = r src =" about: blank "frameborder =" NO "> ");
Print ("</frameset> n ");

// The information sending screen, information command center, and all commands must be sent here
Print ("<frame name = d src = send. php? Name = $ name & pass = $ pass scrolling = 'no
'Frameborder = "NO" noresize> n ");

// Passively update the screen to process sent information
Print ("<frame src =" about: blank "name =" bl "> n ");

/Actively update the screen to display the chat information of yourself and other chat friends
Print ("<frame src =" about: blank "name =" flush "> n ");

// Check whether the screen is online. Handle abnormal exit, such as crashes or disconnection.
Print ("<frame src =" about: blank "name =" check "> n ");
Print ("</frameset> n ");

The display order is very important because the programs on different pages are related. As you can see, I only have to send the page not about: blank, to display other pages, you must call the sending page before starting.


Command Center

This is the command center of the chat room. All commands must be issued here.
1. The following is the basic sending form code.

<Form name = inputform action = 'messagesend. php' target = 'bl' onsubmit = 'Return (checksay (); 'method = POST>

<?
// The following two parameters are used to verify the correctness of the information.
Print ("<input type = 'siden' name = 'name' value = '$ name'> n ");
Print ("<input type = 'ddn' name = 'pass' value = '$ pass'> n ");
?>

// Chat object. Add the readonly attribute.
<Input type = "text" name = "talkto" size = "10" maxlength = "20" readonly value = "all">

// Content sent from the last chat
<Input type = 'siden' name = 'message' value = ''>

// Send the form text box
<Input type = "text" name = "msg" maxlength = "120" size = "34">

<Input type = "submit" name = "Submit" value = "send">

</Form>

2. Check the js of the sent content

Var dx = '';
Function checksay ()
{

// Do not send blank speeches
If (document. inputform. msg. value = '')
{
Document. inputform. msg. focus ();
Return false;
}

// Repeated speeches are not allowed. The content is the same and the objects are the same.
If (document. inputform. msg. value = document. inputform. message. value)
& (Document. inputform. talkto. value = dx ))
{
Alert ('Statement cannot be repeated ');
Document. inputform. msg. focus ();
Return false;
}

// The interval between two speeches cannot be less than 1 second, or the interval between the two speeches * 3
T2 = (new Date (). getTime ()/1000;
If (t2-t1) <1) | (t2-t1) * 3 <document. inputform. msg. value. length ))
{
Document. inputform. msg. focus ();
Return false;
}

// Update Time
T1 = t2;

Document. inputform. showsign. value = 1;

// Save the content of the previous speech
Document. inputform. message. value = document. inputform. msg. value;

// Clear the speech content
Document. inputform. msg. value = '';

// Save the speaker
Dx = document. inputform. talkto. value;

// Locate the focus
Document. inputform. msg. focus ();

// Return
Return (true );
}

3. Call the information sender program to publish information that the chatbot has entered.

<Script>
Parent.bl.doc ument. open ();
Parent.bl.doc ument. write ("<meta http-equiv = 'refresh' content = '0; url = messagesend. php? Name = <? Print ($ name);?> & Action = enter & pass = <? Print ($ pass);?> '> ")
Parent.bl.doc ument. close ();
</Script>

The speech is processed by messagesend. php. Note that the output object is bl, that is, the name of the Framework for processing the speech. This ensures that the content on the page of the speech framework is complete.

Expressions and actions

Emotions and actions greatly enrich the fun of chatting. Generally, chat rooms are sent in two ways.

(1) button menu Method

Select from a fixed drop-down menu, find your satisfied expression, select it, and press the send button to send it.

(2) manually enter the code

For example, Netease's manual input // hello represents a welcome action, and // bye represents a goodbye action.
Here we will introduce the specific implementation of the menu. Do not introduce manual input! Haha! Unless you cannot remember those...

1. Select the implementation of emoticons from the drop-down menu.

For the convenience of expansion, we have created a data file for emojis, which will be very convenient for future expansion.

The format of the emoticon action file is as follows ($ split represents the delimiter ):

// 1234 $ split "1234567, where are my friends? 1234 !!!!!"
//? $ Split looks at the object with doubts...
//?? $ Split: Yes, I have broken my head and I have not come up with a solution.
//??? $ Split what's going on? What the hell is going on?

The previous // 1234 represents the emoticon action code. The separator represents the emoticon action displayed. Note that the two words of the object will be replaced with the name of the speaker during display.

This code is used to write the corresponding emoticon code selected from the menu to the sending bar.

<Script>
Function changemote ($ newemote)
{
Document. inputform. msg. value = $ newemote
}
</Script>

This code generates a dynamic menu

<Select name = "select" onchange = "changemote (this. options [this. selectedIndex]. value)">
<Option value = "0" selected> action </option>
<?
$ Emotemsg = file ($ emotefilename );
For ($ I = 0; $ I <count ($ emotemsg); $ I ++)
{
$ Msg = split ($ split, $ emotemsg [$ I], 99 );
Print ("<option value = $ msg [0]> $ msg [1] </option> ");
}
?>
</Select>

In this way, the process of selecting an action expression from the menu is completed.

2. Processing of emoticon actions in the speech processing program

Messagesend. php

<?

// Read the emoticons File
$ Emote3 = file ($ emotefilename );
$ Emote3number = count ($ emote3 );
For ($ kk = 0; $ kk <$ emote3number; $ kk ++)
{

// Separate each emotion
$ Emote = split ($ split, chop ($ emote3 [$ kk]), 99 );

// If the speech content is equal to the emoticons
If ($ message = $ emote [0])
{

// Replace the object in the emoticon action with the actual chat Object Name
$ Emote [1] = ereg_replace ("object", "<font color = red> $ talkto </font>", $ emote [1]);

// Change the speech content to the action expression content
$ Message = "<a href = javascript: parent. cs ('$ name') target = d> $ name </
> ". $ Emote [1];
Break;
}
}
?>

In this way, we can implement expressions and actions. If we do a program function that automatically adds emotices, it will increase the entertainment of chat!

Post Diagram

If you can add some beautiful pictures in the chat text .......
The image code is generated in the same way as the emoticons. You can select the menu or manually enter the Image Code. Here, only the format and code are provided, and no explanation is given. Check the emoticons in the action section.

1 file format

// $ Picturefilename

1$splitcoffee West server ?splitxw20151.jpg $ split
2$splitblack $$splitxw201534.jpg $ split

Number + name + image name +

2 Programs

In my chat room, the image is displayed by // gift + number. Note that there are three backslashes, which are different from emoticons.

<?
// Determine whether the first 7 characters in the speech are /// gift
If (substr ($ message, 0, 7) = "// gift ")
{

// Obtain the image number, which is a string of 2 characters starting from 7th characters (Note: The character number starts from 0)
$ Id = substr ($ message, 7,2)-1;

// Read the image file
$ Giftmsg = file ($ picturefilename );

// Determine whether the serial number is valid
If ($ id> = 0) & ($ id <count ($ giftmsg )))
{
// Split the image rows
$ Gift = split ($ split, $ giftmsg [$ id], 99 );

// Generate the image's speech content
$ Message = "<a href = javascript: parent. cs ('$ name') target = d> <font col
Or = $ namecolor> $ name </font> </a> to <a href = javascript: parent. cs ('$ talkt
O ') target = d> $ talkto </a> a $ gift [1] 0 height = 60 border = 0> </font> ";

// Mark of successful Image Generation
$ Specialsign = 1;
}

}

Implementation of confidential discussion

Each chat room provides a chat function to facilitate those chat friends who need to communicate privately. Here we will introduce the methods for implementing private chat in my chat room as follows:

1. Processing of sent information

Every private chat is displayed on the screen of the user and the private chat object, and others cannot see it. Here, we will process the speech content and save it in the speech file!

// $ Split is the Separator

Messagesend. php

<?
// Determine whether to speak privately
If ($ secret = "on ")
{
// Mark the speech <! -- + Private chat tag + Object + speaker + --> in which + represents the Separator

// The first one marked as secret indicates private chat, followed by the chat object and its own name, so that the two can see
$ Message = "<! -- $ Splitsecret $ split $ talkto $ split $ name $ split --> <font c
Olor = ff0000> password discussion </font> $ message ";
}
Else
{

// If the first object is marked as "open", the object and its own name will be followed.
$ Message = "<! -- $ Splitopen $ split $ talkto $ split $ name $ split --> $ message"

}

// Save it to the file
?>

2. Private Chat Display Method

After reading each new speech, process and judge it first, and actively refresh the program.

Messageflush. php

<?
// Separate the speech content
$ Tempmessage = split ($ split, $ message [0], 99 );

// If the speaker is not a private conversation, or the target user is a private chat, or the user who sends the private chat is himself, this sentence is displayed; otherwise, it is not displayed.
If ($ tempmessage [1]! = "Secret") | ($ tempmessage [2] = $ name) | (
$ Tempmessage [3] = $ name ))
{

// Display private chat
Print ("parent.u.doc ument. writeln (" $ message [0] "); rn ");
}
?>

Through this simple method, we implement private chat,

Note:

Before saving the file for processing, the judgment text before and after the speech has <! -- And --> in this way, you don't have to deal with it when the screen is displayed!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.