user123_456
user123_456

Reputation: 5805

Accessing SESSION variables from another php file

I want to access the session variable which I declared in the another php file.

How can I do that?

Here is what I did.

test.php

$_SESSION['SESS_VERSION'] = $member['Version'];
session_write_close();
header('location: '.$_SESSION['SESS_VERSION']);

This session variable is working and I am correctly redirected to another page.

On that page for example:

test2.php

I am calling a php script from javascript to return me a JSON formated data.

What I was trying to do in that test3.php script is to access a session variables from test.php

Here's the code:

<?php
header("Content-type: application/json; charset=UTF-8");

echo '{ "results" : [ ';

$result = dbMySql::Exec("SELECT 
    m.data1
    v.data2,
    k.data3
FROM {$_SESSION['SESS_MAIN_BASE']} m, {$_SESSION['SESS_SECOND_BASE']} v, {$_SESSION['SESS_THIRD_BASE']} k");
$result_array = array();
?>

Why I can't access any of the session variables on this php page? Maybe my syntax is not correct. But this is the error that I am getting:

Warning: Cannot modify header information - headers already sent 

And of course error that variables are empty.

Upvotes: 2

Views: 12601

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42736

you need

session_start()

at the top of each of your php scripts otherwise the session variable is meaningless across php files.

Also you are getting the Cannot Modify header error because you have

Here's the code:

being sent to the browser before the headers, move all header functions before any content

Upvotes: 6

Related Questions