2016-02-07 51 views
0

我有我在哪裏顯示用戶帖子的網頁,並在其中,我包括在PHP文件,從數據庫獲取這些帖子。我這樣做是爲了可讀性的目的,也因爲這包括php文件用於做ajax調用。在開始時,我正在重新生成一個新的會話,但在包含它的文件中還重新生成了一個新的會話。session_regenerate_id時頭部已經發送

posts_main.php

<?php 

include_once '../includes/connect.php'; 
include_once '../includes/functions.php'; 

sec_session_start(); 

if (login_check($mysqli) == false) { 
    header("location:../login.php"); 
} 
?> 
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Title of the document</title> 
</head> 

<body> 
    <div id="posts"> 
     include('list_posts.php'); ?> 
    </div> 
</body> 

</html> 

list_posts.php

<?php 

include_once '../includes/connect.php'; 
include_once '../includes/functions.php'; 

sec_session_start(); 

if (login_check($mysqli) == false) { 
    header("location:../login.php"); 
} 

//connect to mysql database and echo back results 

?> 

我sec_session_start功能如下:

function sec_session_start() { 
    $session_name = 'sec_session_id'; // Set a custom session name 
    $secure = false; 
    // This stops JavaScript being able to access the session id. 
    $httponly = true; 
    // Forces sessions to only use cookies. 
    if (ini_set('session.use_only_cookies', 1) === FALSE) { 
     header("Location: error.php?err=Could not initiate a safe session (ini_set)"); 
     exit(); 
    } 
    // Gets current cookies params. 
    $cookieParams = session_get_cookie_params(); 
    session_set_cookie_params($cookieParams["lifetime"], 
     $cookieParams["path"], 
     $cookieParams["domain"], 
     $secure, 
     $httponly); 
    // Sets the session name to the one set above. 
    session_name($session_name); 
    session_start();   // Start the PHP session 
    session_regenerate_id(true); // regenerated the session, delete the old one. 

} 

當我啓動主網頁後,我得到了以下錯誤:

Warning: session_regenerate_id(): Cannot regenerate session id - headers already sent in /Library/WebServer/Documents/includes/functions.php on line 24

我意識到這是因爲頭已發送後我打電話session_regenerate_id但後來調用Ajax調用同一個文件時,我需要這個安全的原因包含的文件。

有沒有什麼辦法可以解決這個問題,並保持它在同一時間?

回答

0

問題是session_regenerate_id之前被髮送輸出(如文本或HTML)()被調用。

有,如果你搜索在PHP「已經發送了頭」#2已經討論過這個問題的各種解決方案。在session_regenerate_id()之前查找要發送的輸出或僅使用output buffering

一個簡單的方法來確定正在發送輸出是通過用回波替換session_regenerate_id()和看到的是之前它顯示。

0

你只需要刪除行:

session_regenerate_id(true); 

還是這樣,它會在第一個呼叫工作,並在第二不能不:

if (!headers_sent()) { 
    session_regenerate_id(true); 
} 

爲什麼你會重新生成, session_start已經爲你創建了嗎?

+0

我以爲同樣的事情,我假設他想要生成一個新的會話(不恢復前一個),但不是正確的方式。 – Devon