Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

php - Codeigniter 3 - Access Session from Outside Codeigniter Installation

I can't seem to get session data passed from my codeigniter application back to a script in my includes folder. From what I've read on other answers, I need to set my session_id() to be able to rejoin a session with session_start().

ROOT /
     .. /application
     .. /system
     .. /includes
        .. /Events.php <- I need access from here

Theoretically the code below should work, at least according to other answers, because the new CI session library passes on to native sessions.

session_id($_COOKIE['ci_session']);
session_start();
var_dump($_SESSION); // returns null

Am I misunderstanding sessions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The original answer from @wolfgang1983 Ben Swinburne combined with an answer here: from Atiqur Rahman Sumon

You can include the index.php from any directory, however, you need to change the $system_path and $application_folder variables to match your relative location. Well that's great if you want to completely change your whole application's paths, but I didn't want to, so I just copied the index.php file into the directory I needed to include codeigniter with.

ROOT /
     .. /application
     .. /system
     .. /includes
        .. /Events.php <- I need access from here
        .. /index.php <- Copied CI index with new paths
     .. /index.php

In /includes/index.php:

//$system_path = 'system';
$system_path = '../system';

//$application_folder = 'application';
$application_folder = '../application';

Now you can include codeigniter in your file with the:

<?php
    ob_start();
    include('index.php');
    ob_end_clean();
    $CI =& get_instance();
    $CI->load->library('session'); //if it's not autoloaded in your CI setup
    echo $CI->session->userdata('name');
?>

If you refresh your page now, you would end up with the default controller loaded.

So taking from Atiqur Rahman Sumon's answer, we can define a constant before load to tell the default controller we want to skip it's normal callstack.

ob_start();
define("REQUEST", "external"); <--
include('index.php');
ob_end_clean();

And in your default_controller.php:

function index()
{
    if (REQUEST == "external") {
        return;
    } 

    //other code for normal requests.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...