Automatically start session on every page in php

Are you sick of having to type this code:

   1: <?php session_start(); ?>

On every page which requires user authentication and other aspects which require the use of session variables? Welcome to the club. In this article I’m going to show you some of the ways on how to ditch the freakin’ code.


Use headers

If you’re already using headers then ditch this part. Headers are php files which are used to perform operations which are repeated throughout the program. It can also be used to style every page in your application. Its also a place where you can link the javascript files which you need throughout the entire program that you are creating.

Here’s what a php header file might look like:

   1: <link rel="stylesheet" type="text/css" href="../css/adminstyle.css" />

   2: <link rel="stylesheet" type="text/css" href="../css/grayaccordion.css" />

   3: <link rel="stylesheet" type="text/css" href="../css/validationEngine.jquery.css" />


   5: <script  type="text/javascript" src="../js/grayaccordionload.js"></script>

   6: <script  type="text/javascript" src="../js/topnav.js"></script>

   7: <script src="../js/jquery.validationEngine-en.js" type="text/javascript"></script>

   8: <script src="../js/jquery.validationEngine.js" type="text/javascript"></script>

Its not necessary to put <?php ?> tags on a header file. As you can see in the code above. But if you will need to perform operations which require the power of the server side. Then you should enclose them in <?php ?> tags.

Then you can just import them later, in a different file:

   1: <?php require_once('header.php'); ?>



Edit  php.ini

You can also edit the php.ini file and automatically start a session of every page.

Just search for this line:

   1: ; Initialize session on request startup.

   2: ;

   3: session.auto_start = 0

And change it to this:

   1: ; Initialize session on request startup.

   2: ;

   3: session.auto_start = 1

Restart php, or better yet all the services associated with it (Apache, mysql). Then create a new session without doing the session_start() code.

   1: $_SESSION['student'][] = array('idnum'=>2800570, 'name'=>'natsu');

Make another file and paste this code:

   1: print_r($_SESSION['student']);

See if it outputs the session that you created earlier. It should look like this:

   1: array([0]=>'idnum'=>2800570, 'name'=>'natsu');

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s