amdvb
amdvb

Reputation: 209

php session not working correctly

I have a small messaging system in which I am having a problem with sessions. The problem is that: I have inbox.php and view_inbox.php in which all the messages will be listed on inbox.php and when the user click on one of the messages it will show the message body on the second page.

Also I have a reply button on view_inbox.php to reply to the sender. if user1 sends message to user2 it works fine even with replying each other however when user3 sends a message and I try to reply to user3, it sends to user2 instead of user3.

As you can see below, I am using session to identify to which user to reply to and the problem is that it is inserting the old session(if I had replied to user2 and again try to reply to user3 it doesn;t work).

I can use $_GET variable to avoid this issue but I did not want to show the sender's name in the url. any ideas?

inbox.php

$stmt = $mydb->prepare("SELECT * FROM messages where to_user = ?  and deleted = '' order by id desc");
 $stmt->bind_param('s', $username->username);
 $stmt->execute();

 <?php 
 while ($row = $stmt->fetch_assoc()) {

 $_SESSION['sender'] = $row['from_user']; 

  echo"<a href='view_inbox?messageid=".$row['id']."'>".$row['from_user']."</a>";
?>

view_inbox.php this is just the reply part which is causing the prob.

 $to_user = $_SESSION['sender']; 
if (isset($_POST['replyto']))
 $reply = $_POST['reply'];  {
 if(!empty($reply)){
  $date = date('m-d-Y h:i:s');


$insert = $mydb->prepare("insert into `messages`(`to_user`, `from_user`, `message`, `date`) values(?,?,?,?)");
echo $mydb->error;
$insert->bind_param('ssss', $to_user, $username->username, $reply, $date);
$insert->execute();
}

Upvotes: 0

Views: 166

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173562

Inside inbox.php, the sender session variable keeps getting overwritten in the loop:

while ($row = $max->fetch_assoc()) {
    $_SESSION['sender'] = $row['from_user'];
}

If the last message in the inbox was from sender2, no matter which message you select, it will reply to sender2.

It would be better to let view_inbox.php determine the sender from the messageid parameter.

Upvotes: 0

invisal
invisal

Reputation: 11171

Don't forget to use session_start() before using any $_SESSION


The best way to debug your problem is to inject a print statement inside the loop where you assign the value to the SESSION. Check if your code truly reach to that part.

while(...) {
   echo "Reach here and value is " . $row['from_user'];
   $_SESSION['sender'] = $row['from_user']; 
   echo"<a href='view_inbox?messageid=".$row['id']."'>".$row['from_user']."</a>";
}

Upvotes: 1

Related Questions