Roxx
Roxx

Reputation: 3986

where to declare session_start if multiple files are included?

I have a doubt regarding php session variable declaration.

I have two php files. 1. head.php 2. body.php

head.php

session_start();
$id = $_Session['id'];
$name = $_Session['name'];
some other text like include js include css etc.

body.php

include 'head.php';
echo $id;
echo $uid;

is this correct? or do i need to add session_start(); in body.php file as well.

Upvotes: 1

Views: 1598

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Also if you are including your head.php in many php files you should check session first and then start session. otherwise you will get error.

     if(session_id())
 {
      // session has been started
 }
 else
 {
      // session has NOT been started
      session_start();
 }

Your current code is ok, session start should be in head.php itself

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

TL;DR

You do not need to call the function again after you have called it in your header file.

And Oh, it is $_SESSION , not $_Session

where to declare session_start if multiple files are included?

Before you send any output to the browser. Nothing else matters. There can be hundreds of PHP code lines before that as long as they don't send any output you can call session_start(); after that.

Obviously you will not have SESSION values before that :)

Please elaborate i didn't understand

Don't echo or print etc anything before calling session_start(), not even outside PHP tags. Don't place any html or blank spaces before the PHP tags either. Absolutely nothing should be sent to browser before you call that function.

Wrong usage

<html>
<?php
session_start();
?>

Right Usage

<?php
blahblahblah();   // or nothing
session_start();
echo "<html>";
?>

Upvotes: 6

Related Questions