简体   繁体   中英

How to debug “Warning: session_regenerate_id(): Cannot regenerate session id” in a PHP program?

I am making a messaging system, where the message id is session_id and it is on a session_regenerate id.

It's working fine but, when I changed my template, it keeps on giving errors like below :

" Warning: session_regenerate_id(): Cannot regenerate session id - headers already sent in C:\\xampp\\htdocs\\READS Website MAIN\\Admin\\admin-page\\admin\\message.php on line 24"

Below is my code:

<?php
include('header.php');
include('config.php');


if(isset($_POST['submit'])){

$to = $_POST['to'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$id = session_id();
$sender = $_SESSION['id'];

date_default_timezone_set("ASIA/MANILA");
$date = date('m-d-Y h:i a');




$sql = "INSERT INTO `messages`(`session_id`, `sender`, `recipient`,   
`subject`, `content`, `date`, `stat`) 
VALUES ('$id','$sender','$to','$subject','$message','$date','unread')";
mysql_query($sql) or die(mysql_error());
session_regenerate_id();
if($sql){

echo "<script>alert('Message Sent')</script>";

}else {
echo "<script>alert('error')</script>";
}

}

?>
<div>
<ul class="breadcrumb">
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">User</a>
</li>
</ul>
</div>

<div class="box-content">


<form action='' method='POST'>

To: <select name='to' class="form-control" id="inputEmail3">

<?php $sql = "SELECT * FROM users ";
$result=mysql_query($sql); 
while ($row = mysql_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['Fname']."      
".$row['Lname']." (".$row['user_type'].")</option>";

}

?>
</select>


<div class='col-md-2 col-sm-2 col-xs-5' style='margin-left:150px;    
margin-top:-10px; width:500px;'>

<br>
Subject: <input type='textfield' name='subject' class="form-control"        
id="inputEmail3"><br><br>
Message: <textarea name='message'  class="form-control" id="inputEmail3"             
cols='30' rows='8'></textarea>
<div style = 'margin-left:420px; margin-top: 10px;'>
<input type='submit' name='submit'  value='Send'></div>
</td>




</body>
</html>
<?php include('footer.php');
?>

Make sure you are setting sessions or cookies before any content is sent. Sessions and cookies are set in the header of a response, and since you can't change a header after the content (body) has been sent, you are faced with this warning.

And after reading your code more thoroughly, I must remind you that this code should not be put into the real world, since you're not escaping any queries. Plus that you should really switch to MySQLi or PDO, since the mysql_* functions are deprecated since a few PHP-versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM