如何在codeigniter中强制使用ssl? [英] How to force ssl in codeigniter?
问题描述
我正在使用codeigniter3.如何强制SSL链接到我的网页,以便所有页面都加载有绿色挂锁图标?
I am using codeigniter 3. How do I force SSL connection to my web pages so that all the pages are loaded with the green padlock icon beside it?
注意:如何在不编辑htaccess文件的情况下执行此操作?
Note: How can I do this without having to edit htaccess file ?
推荐答案
从位置application/config/config.php
打开配置文件,并启用或将钩子设置为true,如下所示:
Open config file from location application/config/config.php
and enable or set hooks to true like this:
$config['enable_hooks'] = TRUE;
然后在config
文件夹(即application/config/hooks.php)内创建一个名为hooks.php
的新文件,并在其中添加以下代码:
Then create a new file named hooks.php
inside the config
folder (i.e. application/config/hooks.php) and add the following code in it:
$hook['post_controller_constructor'][] = array(
'function' => 'redirect_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks'
);
现在在application
文件夹(即application/hooks)中创建一个名为hooks
的新目录,然后在hooks
文件夹(即application/hooks/ssl.php)中创建一个名为ssl.php
的新文件.
Now create a new directory named hooks
inside the application
folder (i.e. application/hooks) and then create a new file named ssl.php
inside the hooks
folder (i.e. application/hooks/ssl.php).
在ssl.php
文件中添加以下代码:
Add the following code in the ssl.php
file:
function redirect_ssl() {
$CI =& get_instance();
$class = $CI->router->fetch_class();
$exclude = array('client'); // add more controller name to exclude ssl.
if(!in_array($class,$exclude)) {
// redirecting to ssl.
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
} else {
// redirecting with no ssl.
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
}
}
这篇关于如何在codeigniter中强制使用ssl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!