Jump to content
xisto Community
Feelay

How To Make A Private Message System.

Recommended Posts

Hey!

 

Today, I am going to teach you how to make a Private Message (PM) script in PHP.

 

Before we start, I want to tell you what you should know, and what files we will create.

Then we will continue with the codes, and descriptions. I would like if you learned something from this tutorial.

If you find any errors (Even if I spell something wrong), I would like you to post it in this thread.

 

What you should know:

 

You should know HTML. Just a bit (forms, and maybe a little design if you would like that).

You should know much about PHP and Mysql.

You should know how to create a login-script, because you will need it for this tutorial.

if you don't know how to create one, you can check a very simple login-script tutorial that I made some time ago:

How to create a login-script

 

Now.. Lets start with the Mysql table, or? Thanks to Vujsa I could make this one :)

 

messages.SQL

 

CREATE TABLE `messages` (  `message_id` int(11) NOT NULL auto_increment,  `from_user` varchar(65) character set latin1 collate latin1_general_ci NOT NULL,  `to_user` varchar(65) character set latin1 collate latin1_general_ci NOT NULL,  `message_title` varchar(65) NOT NULL,  `message_contents` longtext NOT NULL,  `message_read` int(11) NOT NULL default '0',  PRIMARY KEY  (`message_id`)) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=21;

The things we have done here is:

We have created a table named 'messages'.

then we have created some columns:

message_id : This is the column where the ID of the message will be stored. we will need this when we will get the messages from the table.

from_user : This is the column where the name of user that sent the message will be stored.

to_user : This is the column where the name of the user that the message was sent to is stored.

message_title : This is where the title of the message will be stored.

message_contents: This is where the content of the message will be stored.

message_read : This will check if the message id read or not.

 

Save this in a file and call it "messages.SQL" or something.

 

Now after you have created the table (if you don't know how to import SQL files, you should go and learn :))

You should start with the inbox file.

 

inbox.php

 

<?phpsession_start();require "database.php";$userfinal=$_SESSION['session_name'];// get the messages from the table.$get_messages = mysql_query("SELECT message_id FROM messages WHERE to_user='$userfinal' ORDER BY message_id DESC") or die(mysql_error());$get_messages2 = mysql_query("SELECT * FROM messages WHERE to_user='$userfinal' ORDER BY message_id DESC") or die(mysql_error());$num_messages = mysql_num_rows($get_messages);// display each message title, with a link to their contentecho '<ul>';for($count = 1; $count <= $num_messages; $count++){	$row = mysql_fetch_array($get_messages2);	//if the message is not read, show "(new)" after the title, else, just show the title.if($row['message_read'] == 0){	echo '<a href="read_message.php?messageid=' . $row['message_id'] . '">' . $row['message_title'] . '</a>(New)<br>';}else{echo '<a href="read_message.php?messageid=' . $row['message_id'] . '">' . $row['message_title'] . '</a><br>';}}echo '</ul>';echo '<form name="newmsgfrm" method="post" action="new_message.php">'; echo '<input type="submit" value="Send a New Message">'; echo '</form>';echo '<form name="backfrm" method="post" action="index.php">'; echo '<input type="submit" value="Back to Home">'; echo '</form>';?>

simple isn't it?

The first things we do are very simple.

We start the session.

We require the database.php file (the database.php is the file where the mysql connections and stuff is stored. you should know how to created such a file. if you don't know, i'll create one in the end of this tutorial, only for you ;))

then we create a variable for the set session, to make it easier to write.

Then we create some variables.

the $get_messages is the variable where the message id is stored.

the $get_messages2 is the variable where all the messageinfo is stored.

Then we create a simple for-loop that will show all the messages that is sent to the user that is logged in(check w3schools or google or whatever, if you don't know what that is.).

the first thing we do here is:

Check if the message is read.

If it isn't, the loop will add "(new)" after the message title. else, it will just show the message title.

The last thing we do is:

Add 2 buttons. One to send a new message, and one to go back to the home-page.

 

Now lets begin with the new message file.

 

new_message.php

 

<?phpsession_start();require "database.php";$userfinal=$_SESSION['session_name'];$user=$userfinal;?><form name="message" action="messageck.php"method="post"><input type="text" name="message_title"> Title: <br><input type="text" name="message_to"> To: <br>Message: <br><textarea rows="20" cols="50" name="message_content"></textarea><?phpecho '<input type="hidden" name="message_from" value="'.$user.'"><br>';?><input type="submit" value="Submit"></form>

The things we do here, are also very simple.

The first things we do is:

Start the session.

require the database.php file.

create a variable for the set session.

then we create the forms.

a textbox for the message title.

a textbox where you write to who you want to send the message.

a textbox for the message content.

and then, you see this line:

<input type="hidden" name="message_from" value="'.$user.'">

This is a hidden line, and the user will not see it.

this invisible textbox, includes the name of the user that is writing the message.

remember that we created a variable named $user that includes the session name?

the session name, includes the username. and where the "value" is "$user", the username is inserted by the code.

then we create a normal submit box, that will send the message, and we are done with this file.

 

Now we should create a file, that checks if the sent message is ok to send.

 

messageck.php

 

<?phpsession_start();require "database.php";$title=$_POST['message_title'];$to=$_POST['message_to'];$content=$_POST['message_content'];$from=$_POST['message_from'];$time=$_POST['message_date'];$ck_reciever = "SELECT username FROM user WHERE username = '".$to."'";				if( mysql_num_rows( mysql_query( $ck_reciever ) ) == 0 ){die("The user you are trying to contact don't excist. Please go back and try again.<br><form name=\"back\" action=\"new_message.php\"method=\"post\"><input type=\"submit\" value=\"Try Again\"></form>");}elseif(strlen($content) < 1){die("Your can't send an empty message!<br><form name=\"back\" action=\"new_message.php\"method=\"post\"><input type=\"submit\" value=\"Try Again\"></form>");}elseif(strlen($title) < 1){die("You must have a Title!<br><form name=\"back\" action=\"new_message.php\"method=\"post\"><input type=\"submit\" value=\"Try Again\"></form>");}else{mysql_query("INSERT INTO messages (from_user, to_user, message_title, message_contents, message_date) VALUES ('$from','$to','$title','$content','$time')") OR die("Could not send the message: <br>".mysql_error()); echo "The Message Was Successfully Sent!";?><form name="back" action="inbox.php"method="post"><input type="submit" value="Back to The Inbox"></form><?php}?>

now you guys should know the first things we do (starting a session and including the database file.).

Now the second thing we do in this script is creating a variable for every single form in the last script.

We create a variable for the message title, content, "to-user" and so on.

We do also create a variable that selects the username that was set in the "to-user" form.

Then we create a if-statement that checks if the user excists. If not, the code will write an error message, and show you a back-button.

Then it will check if there is any content and title. If not, an error message will be written, and a back-button will be shown.

Else if everything worked as it should work, the message will be inserted in the database table that we created earlier.

 

Now we should create a file that will let the user read the message, or ;)?

 

read_message.php

 

<?phpsession_start();$userfinal=$_SESSION['session_name'];require "database.php";$messageid = $_GET['message'];$message = mysql_query("SELECT * FROM messages WHERE message_id = '$message_id' AND to_user = '$userfinal'");$message=mysql_fetch_assoc($message);echo "<h1>Title: ".$message['message_title']."</h1><br><br>";echo "<h3>From: ".$message['from_user']."<br><br></h3>";echo "<h3>Message: <br>".$message['message_contents']."<br></h3>";echo '<form name="backfrm" method="post" action="inbox.php">'; echo '<input type="submit" value="Back to Inbox">'; echo '</form>';?>

you know the first things we do here.

 

the second things I do is creating a variable that includes the value from the"<a href="read_message.php?messageid=' . $row['message_id'] . '">" in the inbox file.

then I create a variable that will include all the info about the message with that id (and check if the post is sent to the user or not [if it isn't, the post will be empty, else, the contents will be shown]).

then I create three echos.

The first one will write the title of the message.

the second one will write the name of the user that sent the message.

the last one will write the content of the message.

 

then I just add a back-button. simple isn't it?

 

now for those of you who don't know how to make a database.php file, here it is, but I won't comment it.

 

database.php

 

<?phpmysql_connect ("localhost", "mysql_username", "mysql_password") or die ('I cannot connect to the database because: ' . mysql_error());mysql_select_db ("db_name");?>

Remember!

If you find any errors, post them here, and I will try to fix them as soon as possible.

I have tryed this PM system, and it works!

 

Thanks for reading! //Feelay

Edited by Feelay (see edit history)

Share this post


Link to post
Share on other sites

Nicely done Feelay.

 

I like when someone takes the time to write a tutorial about something they just learned since the learning experience is still fresh in their minds. As a result, the tutorial usually includes information that many time would be left out because the writer assumes that the reader has pre-existing knowledge of the subject.

 

I would suggest one security addition.

In read_message.php, you don't check the reader's id which means that if I were to type the following url in my browser:

domain.com/read_message.php?messageid=221

Then I could read that message even if it didn't belong to me.

 

Change your query to something like this:

$message = mysql_query("SELECT * FROM messages WHERE message_id = '$messageid' AND to_user = '$userfinal'");

Which will only get the message if the message id and the user id match the message id requested. If the query returns empty, just do an error message that the "message could not be found" or "you are not authorized..."!

 

vujsa

Share this post


Link to post
Share on other sites

thanks Vujsa :) I've been trying to do that security thing, but an error about the letter (small and big letter) occur. I'll change that as soon as I've tryed it :)

Share this post


Link to post
Share on other sites

thanks Vujsa :) I've been trying to do that security thing, but an error about the letter (small and big letter) occur. I'll change that as soon as I've tryed it :)

If you changed to user_id (numeric) instead of using usernames, then you will eliminate a lot of potential errors that could pop up.
Most systems use a numeric user_id instead of a username that way the input data is formated in a predictable way and prevents errors that can come up with lower/upper case issues, special characters, etc...

You probably have a user table with usernames, id's, email, etc.

Just use that table as the translator! The queries are more complex but just as quick. You basically have to "JOIN" tables together to use the information all at the same time.

Here is an example of such query using the PM table and the user table!

"SELECT user_to.id, user_to.username, user_from.id, user_from.username, msg.message_id, msg.to_user, msg.from_user, msg.message_title, msg.message_contents, msg.message_read FROM message AS msg LEFT JOIN users AS user_to ON user_to.id = msg.to_user LEFT JOIN users AS user_from ON user_from.id = msg.from_user WHERE messageid = '$msgid' AND user_to.id = '$session_user_id'"



I know it is complex but, here is your data from the query:
user_to.id = 22
user_to.username = vujsa
user_from.id = 1
user_from.username = Feelay
msg.message_id = 321
msg.to_user = 22
msg.from_user = 1
msg.message_title = My Title
msg.message_contents = Hi vujsa, thanks for the widget!
msg.message_read = 1

That assumes that my id is 22 and your id is 1.

You can then use the returned data however you like.

It is much easier to do (depending on your point of view) to use aliases for each item like so:

"SELECT msg.content AS Contents from ..."


this just give you easier names to use.

For information about JOIN, see here:
http://dev.mysql.com/doc/refman/5.7/en/join.html

For more information about aliases, see here:
http://dev.mysql.com/doc/refman/5.7/en/select.html

Hope this helps,
vujsa

Share this post


Link to post
Share on other sites

way to complex :) But I have found another solution.. I'll will change to this when I really know how to use it.

The thing that will happen is:

If the user is trying to view someone elses message, the message will be empty.

 

edit:

I've chnaged the tutorial now. if the user is trying to view someone elses message, it will be empty.

it was acctually the first thing you said that was the solution vujsa :) But I couldn't make an error occur if the message didn't belong to the user.. my brain is not working hard enough ;)

Edited by Feelay (see edit history)

Share this post


Link to post
Share on other sites

when you read the message? maybe because you just copy pasted everything :mellow:I don't say you did. I just said you MAYBE did :Din read_message.php and new_message.php try to change the $userfinal=$_SESSION['session_name'];to the name of the session you are using..BTW :o sorry for the late answer (A)

Share this post


Link to post
Share on other sites

Very nice tutorial. Combined with AJAX on the client-side, this would be a great addition to any Web 2.0 site. Even without AJAX, this is a great way to add interactivity to your site. I have learned many things from reading through your code and I am still learning new things about PHP and MySQL. I haven't found a use for it yet for my own purposes but I hope to soon.Thanks for posting this awesome tutorial.

Share this post


Link to post
Share on other sites

Hello,i try to do your system in my site, i change the $_SESSION in al the files,in inbox.php it's work great ! i can see the messages, in new_message.php work too, i can send a message.i have just a 2 problmes please help me,in read_message.phpi cant see the what people wrote, i cant see who sending the message!in PHPMYADMIN, it's OKi see the fields good !from_userto_usermessage_contentand all...but in the site i cant see anything in read_message.php ... please Help me.another tiny problem, when i didnt open a message it's write "New" near to the Titleand when i open the message and go back to inbox, it's still write New near to title,it's not update the mysql...please help me with this to problems !thanks !

Share this post


Link to post
Share on other sites

Hello,i try to do your system in my site, i change the $_SESSION in al the files,
in inbox.php it's work great ! i can see the messages, in new_message.php work too, i can send a message.
i have just a 2 problmes please help me,
in read_message.php
i cant see the what people wrote, i cant see who sending the message!
in PHPMYADMIN, it's OK
i see the fields good !
from_user
to_user
message_content
and all...
but in the site i cant see anything in read_message.php ... please Help me.

another tiny problem, when i didnt open a message it's write "New" near to the Title
and when i open the message and go back to inbox, it's still write New near to title,
it's not update the mysql...

please help me with this to problems !

thanks !


I have the exact same problem! And I believe the problem is this line $messageid = $_GET['message']; as it isn't getting the id. so change it to $messageid = $_GET['messageid'];
Edited by sam_benne (see edit history)

Share this post


Link to post
Share on other sites

hey guys, sorry to open up an old thread, but just wondered if anyone could help me get this working?inbox.php shows message title and (new) and if i click one through to read_message.php?messageid=28 I just getTITLE:FROM:MESSAGE:[back to inbox]I've checked phpmyadmin, and the from_user is empty as well as the date (i added this field manually because it wasn't in the .sql file.Any help would be appreciated I'm new to mysql.Thanks guys :o

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | 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.