2015-06-23 42 views
3

我似乎無法獲得從我的codeigniter應用程序傳遞迴我的includes文件夾中的腳本的會話數據。從我讀過的其他答案中,我需要將我的session_id()設置爲能夠重新加入session_start()的會話。Codeigniter 3 - 從外部Codeigniter安裝訪問會話

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

理論上下面的代碼應該工作,至少根據其他的答案,因爲新的CI會議庫傳遞給本地會話。

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

我誤會嗎?

+0

[從外部文件訪問笨會話值]的可能的複製(HTTP:/ /stackoverflow.com/questions/7926455/access-codeigniter-session-values-from-external-files) –

回答

4

從@ wolfgang1983 Ben Swinburne一個答案在這裏結合原來的答案:從Atiqur Rahman Sumon

您可以包含任何目錄index.php,但是,您需要更改$system_path$application_folder變量的相對匹配位置。那麼如果你想徹底改變你的整個應用程序的路徑,那就太好了,但我不想,所以我只是將index.php文件複製到我需要包含codeigniter的目錄中。

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

/includes/index.php

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

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

現在,您可以與您的文件笨:

<?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'); 
?> 

如果你現在刷新頁面,你會結束與默認控制器加載。

因此,從Atiqur Ra​​hman Sumon的回答中,我們可以定義一個常量,以告訴默認控制器我們想要跳過它的正常調用堆棧。

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

而在你default_controller.php

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

    //other code for normal requests. 
} 
+1

這個答案的帽子。真正保存了大量的混淆,爲什麼一個AJAX請求加載我們的應用程序的登錄屏幕的HTML! – PaulSkinner

+0

@PaulSkinner很高興能幫到你! – acupajoe

+0

對於那些想將CI用作其後端框架的人來說,這是最好的解決方案:)。像我一樣,我需要使用WordPress作爲我的前端,我需要一個硬代碼添加一個新的登錄儀表板,這將發生。 –

0

提高對@ acupajoe的回答,您不必複製粘貼的CI index.php。相反,include部分變成這樣:

<?php 
    ob_start(); 
    define("REQUEST", "external"); 
    $temp_system_path = 'path/to/system/folder/from/external/file'; 
    $temp_application_folder = 'path/to/application/folder/from/external/file'; 
    include('path/to/index.php/file/from/external/file'); 
    ob_end_clean(); 
    $CI =& get_instance(); 
    //... 
?> 

然後在index.php改變:

$system_path = isset($temp_system_path) ? $temp_system_path : 'system'; 

$application_folder = isset($temp_application_folder) ? $temp_application_folder : 'application';