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! BenProgramUse 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 sectionCodeOpen a howtodo window with no status bar and 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> <HR> ');

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.

EmotionCompositionThe format of the parts 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.