Honesty Rocks! truth rules.

How To Make A Private Message System.

HOME      >>       Programming

Feelay

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


vujsa

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


Feelay

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 :)


vujsa

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


Feelay

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 ;)


iGuest

Yeah this would be cool but i i was to make a private message system i would do it inside of a members system Nice


Feelay

This is inside of a members system :) But I didn't have time to write it, and between, I have already made members system tutorials :)


Normano

Thanks, im searching for a script like this in years:) :(
uum... i got a problem, it only say this

Title:From:Message:[button]
Please help

Feelay

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)


FirefoxRocks

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.


yyhananyy

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 !


sam_benne

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'];

yyhananyy

it does'nt work :rolleyes:i dont know what to do !help please !


liod

Hey, i like your AJAX. I can create ligin and PM script but i dunno about combining with ajax.Thank you. :rolleyes:


joneejay

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


yordan

h the from_user is empty as well as the date (i added this field manually because it wasn't in the .sql file.

Where is this .sql file coming from? Did you get it from the feelay starter topic text ?

iGuest

Maybe use isset?How To Make A Private Message System.

hey Feelay,

I was just wondering... I'm pretty new with this MySQL and PHP stuff, but wouldit be possible for the read_message.Php to have code that checks if isset($message) and then echoes the message and message information, like who sent it and when, if that variable is set (and that would be based on the checking whether the user logged in is the same as the to_user and if the session is valid). Else, it could echo an error saying something like, "You are not allowed to view this message because: 1. You are not logged in, or 2. You are trying to view someone else's message!"

This is just a thought. I'm not sure it would work in practice, so let me know if they can use this successfully! Thanks

-reply by newPHP-er

 


qiqiprop

Hai,Thanks for the tutorial. It's very helpful. But there is one thing that I would like to know. How to display that you got a new message on page? I know it is something related with the "message_read" variable of that table but you didn't mention how it works..


iGuest

Very nice, thanks.How To Make A Private Message System.

I understand that your example code is an extremely bare version, but anyone would doesn't know how to properly handle user input could get thmeselves into a ton of problems from SQL Injection attacks for one.

When handling user input, no matter what it is, always check it and sanitise it. Here's a quick example of my sanitisetxt() function:

function sanitisetxt($txt_string, $maxlength=0, $addslashes=true) {  // Handy function for all non-html user-provided strings  $returntext = trim(strip_tags($txt_string));  if ($addslashes) $returntext = addslashes($returntext);  if ($maxlength) $returntext = substr($returntext,0,$maxlength);  return $returntext;}

I'm sure you can do plenty more in this function, but this is a basic version, you could add in preg_replace() etc. To call the function is simple:

$title=sanitisetxt(@$_POST['message_title'], 50, true);$to=sanitisetxt(@$_POST['message_to'], 50);$content=sanitisetxt(@$_POST['message_content']);$from=sanitisetxt(@$_POST['message_from'], 50);

The @ symbols stop PHP from adding an error to your logs ifthe variable hasn't been provided.

 Anyway, thanks for the example, I will be basing my new PMing system on it (albeit more featureful).

-reply by ahdkaw

iGuest

i get this errorHow To Make A Private Message System.

I get this errorCould not send the message: Unknown column 'message_date' in 'field list'

-reply by jacob