April 7, 2012

PHP header("Location: $url");

Question by Miomir Dancevic

Possible Duplicate:
Headers already sent by PHP

Here i have strange problem to protect my pages , to check is session started, if not redirect to login,

    <?php 
require_once ('includes/config.inc.php'); 

// Start output buffering:
ob_start();

// Initialize a session:
session_start();

// Check for a $page_title value:
if (!isset($page_title)) {
    $page_title = 'User Registration';
}

// If no first_name session variable exists, redirect the user:
if (!isset($_SESSION['first_name'])) {

    $url = BASE_URL . 'index.php'; 
    ob_end_clean(); // Delete the buffer.
    header("Location: $url");
    exit(); // Quit the script.

}
?>

I got this error: on line 8:

session_start() [function.session-start]: Cannot send session cache limiter – headers already sent

Can someone post a good solution to check if the session is started, and if not redirect to login page else stay on page??
Txanks

Answer by Starx

Whenever, you see headers already sent, that means somethings is being output before the PHP could send the headers.

In your case, it is the additional sources before the PHP tag as Oli Charlesworth said.

May 22, 2010

PHP Link to session_destroy

Question by nosedive25

I need to make a link that when clicked will run this in php:

session_destroy();

I know how to make a link in html, but I don’t know how to make it interact with php. Thanks for any help.

Answer by Starx

For an example, you want to use this script for logging out.

Your HTML has to be something like this for “index.php” (just an example)

<a href="logout.php">Log Out</a>

Then on the “logout.php”

session_start(); //to ensure you are using same session
session_destroy(); //destroy the session
header("location:index.php"); //to redirect back to "index.php" after logging out
exit();

In case you want to use JavaScript, I can tell you that too?

...

Please fill the form - I will response as fast as I can!