Skip to content
Advertisement

How to Start custom session function inside a class

I am learning php.

I have a class and a function to start a custom session like the following, Now how can I use the said custom session_start in every php page? please help. my code is like

<?php
// myclass.php

class abcd{
    function sec_session_start() {
    $session_name = 'sec_session_id';   // I have Set a custom session name
    $secure = false;  

    $httponly = true;

    if (ini_set('session.use_only_cookies', 1) === FALSE) {
    $err='Could not initiate a safe session (ini_set)';
    $err = Encryption::encode($err);        
        header("Location: ../login.php?error_msg=".$err);
        exit();
    }

    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
    //session_set_cookie_params(time()+3600,
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);
    // Sets the session name to the one set above.
    session_name($session_name);    
    session_start();
    session_regenerate_id(true);  
    }
}

?>

In this case the following error is showing : Notice: A session had already been started – ignoring session_start()

myphp page is below –

<?php
// mypage.php

include_once "myclass.php";
$mevalue = new abcd;
$mevalue->sec_session_start();

code code code

?>

Please help me to solve this.

Advertisement

Answer

A session should last throughout the page visit and not be renewed on each page, e.g. a user logs in once and this is stored into a session so the user doesn’t need to login again for each new page or click.

Mostly a session starts if someone visits your page and remains until the user leaves the page -> closing the session.

The best way is to check if a session is open for this user and only start a session if the user doesn’t have one.

To close a session one can use

 session_write_close ( void ) : bool

Source

With this you can update your code to have a get_session function. In this function you can check if a session exists and use that one, if not start a new one

class abcd{
    function init_session()
    {
        if (!isset($_SESSION)) {
            $this->sec_session_start();
        }
    }

    function sec_session_start() {....

And in your page

$mevalue->init_session();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement