CI框架源码阅读---------Config.php
文件地址:./system/core/Config.php
主要作用:管理配置
1.成员属性$config 所有已加载配置的值的列表
2.成员属性$is_loaded 所有加载配置文件的列表
3.成员属性$_config_paths 当需要加载配置文件的时候搜索路径的列表
4.__construct() 构造方法程序会首先自动执行这个方法
它所做的内容主要有两个
a)获取配置赋值给成员属性$config
b)设置配置中的base_url
5.load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE)
加载配置文件
$file 是你自定义的配置文件的文件名,这个文件名没有 .php 的扩展名.
$use_sections
如果你需要加载多个自定义配置文件,一般情况下它们会被合并成一个数组。然而,如果在不同的配置文件中存在同名的索引,那么会发生冲突。为了避免这个问题,你可以把第二个参数设置为 TRUE ,这可以使每个配置文件的内容存储在一个单独的数组中,数组的索引就是配置文件的文件名。
$fail_gracefully
允许屏蔽当配置文件不存在时产生的错误信息:
(0)过滤并设置$file 变量
(1)初始化$founf 为FALSE 用于判断文件是否存在
(2)初始化$loaded为FALSE 用于判断文件是否被加载
(3)检测文件路径如果有环境变量添加环境变量
(4)进入foreach遍历文件路径,并查找文件是否被加载和存在
(5)如果文件不存在跳出foreach循环
(6)加载文件
(7)判断$config是否存在,这个$config 应该是加载的文件中定义的
(8)判断$use_sections 如果为真则将使每个配置文件的内容存储在一个单独的数组中,数组的索引就是配置文件的文件名。
如果为假则所有配置文件会被合并成一个数组
(9)将文件添加进is_loaded数组中,并销毁$config
(10)$loaded 设置为true log记录 跳出循环
(11)如果loaded为false并且$fail_gracefully不等于true 显示错误日志
6.item() 获取一个配置项
$item 配置项的名字
$index
如果配置是一个数组的时候,这一项是数组索引名字
(1)判断index是否为空
(2)如果index为空,判断$this->config[$item]是否存在,如果不存在返回,存在,赋值给$pref
(3)如果index不为空,判断$this->config[$index]是否存在,判断$this->config[$index][$item]是否存在,将$this->config[$index][$item]赋值给$pref
(4)返回$pref
7.slash_item() 获取一个配置项并添加/
$item 配置项的名字
(1)判断配置项是否存在不存在返回false
(2)判断配置项是否为空如果是空返回''
(3)在配置值的后面添加/并返回。
8.site_url() 该函数得到你网站的 URL,其中包含了你在 config 文件中设置的 "index" 的值。
$uri uri字符串就是访问路径所带的参数
(1) 如果$uri = '' 返回由base_url和index_page组成的url
(2) 判断$this->item('enable_query_strings')真假,并返回不同形式的地址。(这一项是在application/config/config.php文件中配置的。用来区分传参方式,如果为false就是默认的传参方式example.com/who/what/where/。如果为true就是 example.com/index.php?c=controller&m=function这样的传参方式。)
9.base_url() 该函数返回站点的根 URL,可以在这个函数后拼接一个 URL 路径,用以生成 CSS 或图片文件的 URL。
10._uri_string() 构建uri串让site_url(),base_url()两个函数使用。
11.system_url() 该函数得到 system 文件夹的 URL。
12.set_item() 设置一个配置项
13._assign_to_config() 设置多个配置项(以数组的形式key是要设置的配置项的名字,value 是配置项的值)
源码:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------ /** * CodeIgniter Config Class * * This class contains functions that enable config files to be managed * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/config.html */ class CI_Config { /** * List of all loaded config values * * @var array */ var $config = array(); /** * List of all loaded config files * * @var array */ var $is_loaded = array(); /** * List of paths to search when trying to load a config file * * @var array */ var $_config_paths = array(APPPATH); /** * Constructor * * Sets the $config data from the primary config.php file as a class variable * * @access public * @param string the config file name * @param boolean if configuration values should be loaded into their own section * @param boolean true if errors should just return false, false if an error message should be displayed * @return boolean if the file was successfully loaded or not */ function __construct() { $this->config =& get_config(); log_message('debug', "Config Class Initialized"); // Set the base_url automatically if none was provided 假如 if ($this->config['base_url'] == '') { if (isset($_SERVER['HTTP_HOST'])) { $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; $base_url .= '://'. $_SERVER['HTTP_HOST']; $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); } else { $base_url = 'http://localhost/'; } $this->set_item('base_url', $base_url); } } // -------------------------------- /** * Load Config File * * @access public * @param string the config file name * @param boolean if configuration values should be loaded into their own section * @param boolean true if errors should just return false, false if an error message should be displayed * @return boolean if the file was loaded correctly */ function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { $file = ($file == '') ? 'config' : str_replace('.php', '', $file); $found = FALSE; $loaded = FALSE; $check_locations = defined('ENVIRONMENT') ? array(ENVIRONMENT.'/'.$file, $file) : array($file); foreach ($this->_config_paths as $path) { foreach ($check_locations as $location) { $file_path = $path.'config/'.$location.'.php'; if (in_array($file_path, $this->is_loaded, TRUE)) { $loaded = TRUE; continue 2; } if (file_exists($file_path)) { $found = TRUE; break; } } if ($found === FALSE) { continue; } include($file_path); if ( ! isset($config) OR ! is_array($config)) { if ($fail_gracefully === TRUE) { return FALSE; } show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.'); } if ($use_sections === TRUE) { if (isset($this->config[$file])) { $this->config[$file] = array_merge($this->config[$file], $config); } else { $this->config[$file] = $config; } } else { $this->config = array_merge($this->config, $config); } $this->is_loaded[] = $file_path; unset($config); $loaded = TRUE; log_message('debug', 'Config file loaded: '.$file_path); break; } if ($loaded === FALSE) { if ($fail_gracefully === TRUE) { return FALSE; } show_error('The configuration file '.$file.'.php does not exist.'); } return TRUE; } // -------------------------------- /** * Fetch 取得,拿来 a config file item * * * @access public * @param string the config item name * @param string the index name * @param bool * @return string */ function item($item, $index = '') { if ($index == '') { if ( ! isset($this->config[$item])) { return FALSE; } $pref = $this->config[$item]; } else { if ( ! isset($this->config[$index])) { return FALSE; } if ( ! isset($this->config[$index][$item])) { return FALSE; } $pref = $this->config[$index][$item]; } return $pref; } // -------------------------------- /** * Fetch a config file item - adds slash after item (if item is not empty) * * @access public * @param string the config item name * @param bool * @return string */ function slash_item($item) { if ( ! isset($this->config[$item])) { return FALSE; } if( trim($this->config[$item]) == '') { return ''; } return rtrim($this->config[$item], '/').'/'; } // -------------------------------- /** * Site URL * Returns base_url . index_page [. uri_string] * * @access public * @param string the URI string * @return string */ function site_url($uri = '') { if ($uri == '') { return $this->slash_item('base_url').$this->item('index_page'); } if ($this->item('enable_query_strings') == FALSE) { $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix'); return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix; } else { return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri); } } // ------------------------- /** * Base URL * Returns base_url [. uri_string] * * @access public * @param string $uri * @return string */ function base_url($uri = '') { return $this->slash_item('base_url').ltrim($this->_uri_string($uri), '/'); } // ------------------------- /** * Build URI string for use in Config::site_url() and Config::base_url() * * @access protected * @param $uri * @return string */ protected function _uri_string($uri) { if ($this->item('enable_query_strings') == FALSE) { if (is_array($uri)) { $uri = implode('/', $uri); } $uri = trim($uri, '/'); } else { if (is_array($uri)) { $i = 0; $str = ''; foreach ($uri as $key => $val) { $prefix = ($i == 0) ? '' : '&'; $str .= $prefix.$key.'='.$val; $i++; } $uri = $str; } } return $uri; } // -------------------------------- /** * System URL * * @access public * @return string */ function system_url() { $x = explode("/", preg_replace("|/*(.+?)/*$|", "\\1", BASEPATH)); return $this->slash_item('base_url').end($x).'/'; } // -------------------------------- /** * Set a config file item * * @access public * @param string the config item key * @param string the config item value * @return void */ function set_item($item, $value) { $this->config[$item] = $value; } // -------------------------------- /** * Assign to Config * * This function is called by the front controller (CodeIgniter.php) * after the Config class is instantiated. It permits config items * to be assigned or overriden by variables contained in the index.php file * * @access private * @param array * @return void */ function _assign_to_config($items = array()) { if (is_array($items)) { foreach ($items as $key => $val) { $this->set_item($key, $val); } } } } // END CI_Config class /* End of file Config.php */ /* Location: ./system/core/Config.php */

세션 관련 XSS 공격으로부터 응용 프로그램을 보호하려면 다음 조치가 필요합니다. 1. 세션 쿠키를 보호하기 위해 Httponly 및 Secure 플래그를 설정하십시오. 2. 모든 사용자 입력에 대한 내보내기 코드. 3. 스크립트 소스를 제한하기 위해 컨텐츠 보안 정책 (CSP)을 구현하십시오. 이러한 정책을 통해 세션 관련 XSS 공격을 효과적으로 보호 할 수 있으며 사용자 데이터가 보장 될 수 있습니다.

PHP 세션 성능을 최적화하는 방법 : 1. 지연 세션 시작, 2. 데이터베이스를 사용하여 세션을 저장, 3. 세션 데이터 압축, 4. 세션 수명주기 관리 및 5. 세션 공유 구현. 이러한 전략은 높은 동시성 환경에서 응용의 효율성을 크게 향상시킬 수 있습니다.

THESESSION.GC_MAXLIFETIMESETTINGINSTTINGTINGSTINGTERMINESTERMINESTERSTINGSESSIONDATA, SETINSECONDS.1) IT'SCONFIGUDEDINPHP.INIORVIAINI_SET ()

PHP에서는 Session_Name () 함수를 사용하여 세션 이름을 구성 할 수 있습니다. 특정 단계는 다음과 같습니다. 1. Session_Name () 함수를 사용하여 Session_Name ( "my_session")과 같은 세션 이름을 설정하십시오. 2. 세션 이름을 설정 한 후 세션을 시작하여 세션을 시작하십시오. 세션 이름을 구성하면 여러 응용 프로그램 간의 세션 데이터 충돌을 피하고 보안을 향상시킬 수 있지만 세션 이름의 독창성, 보안, 길이 및 설정 타이밍에주의를 기울일 수 있습니다.

세션 ID는 로그인시, 민감한 작업 전에 및 30 분마다 정기적으로 재생되어야합니다. 1. 세션 고정 공격을 방지하기 위해 로그인 할 때 세션 ID를 재생합니다. 2. 안전성을 향상시키기 위해 민감한 작업 전에 재생성. 3. 정기적 인 재생은 장기 활용 위험을 줄이지 만 사용자 경험을 평가해야합니다.

Session_SET_COOKIE_PARAMS () 함수를 통해 PHP에서 세션 쿠키 매개 변수 설정을 달성 할 수 있습니다. 1)이 기능을 사용하여 만료 시간, 경로, 도메인 이름, 보안 플래그 등과 같은 매개 변수를 설정하십시오. 2) call session_start ()를 호출하려면 매개 변수를 발효시킵니다. 3) 사용자 로그인 상태와 같은 요구에 따라 매개 변수를 동적으로 조정합니다. 4) 보안을 향상시키기 위해 안전하고 httponly 플래그 설정에주의를 기울이십시오.

PHP에서 세션을 사용하는 주요 목적은 다른 페이지간에 사용자의 상태를 유지하는 것입니다. 1) 세션은 Session_Start () 함수를 통해 시작되어 고유 한 세션 ID를 생성하고 사용자 쿠키에 저장합니다. 2) 세션 데이터는 서버에 저장되므로 로그인 상태 및 쇼핑 카트 컨텐츠와 같은 다른 요청간에 데이터를 전달할 수 있습니다.

하위 도메인 간의 세션을 공유하는 방법? 공통 도메인 이름에 대한 세션 쿠키를 설정하여 구현. 1. 세션 쿠키 도메인을 서버 측에서 .example.com으로 설정하십시오. 2. 메모리, 데이터베이스 또는 분산 캐시와 같은 적절한 세션 저장 방법을 선택하십시오. 3. 쿠키를 통해 세션 ID를 전달하면 서버는 ID를 기반으로 세션 데이터를 검색하고 업데이트합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!
