[英]How to check if view file exist in codeigniter?
我正在使用 codeigniter v3。
在 controller 文件中,我想檢查視圖文件是否存在。
$file = "login";
$this->load->view($file, array(),true);
代碼給我錯誤
An Error Was Encountered
Unable to load the requested file: login.php
您可以使用file_exists($file);
但是如果有絕對路徑而不對其進行硬編碼。 你可以使用dirname(__FILE__)
$link = dirname(__FILE__) . '/include.php';
if (realpath($link)) {
include($link);
}
原生 PHP 有答案: file_exists()
(請參閱此處的 PHP 文檔)允許您檢查文件系統中是否存在文件。
簡而言之,您需要:
if (file_exists(base_url('views/file.php')))
{
// do something if view file exists
}
else
{
// do some other thing if file is not present
}
有可能覆蓋負責加載視圖的 function
在您的application/core
文件夾中創建一個 class MY_Loader
。
class MY_Loader extends CI_Loader
{
public function view($view, $vars = array(), $return = FALSE)
{
foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val)
{
$$_ci_val = isset($_ci_data[$_ci_val]) ? $_ci_data[$_ci_val] : FALSE;
}
$file_exists = FALSE;
// Set the path to the requested file
if (is_string($_ci_path) && $_ci_path !== '')
{
$_ci_x = explode('/', $_ci_path);
$_ci_file = end($_ci_x);
}
else
{
$_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION);
$_ci_file = ($_ci_ext === '') ? $_ci_view.'.php' : $_ci_view;
foreach ($this->_ci_view_paths as $_ci_view_file => $cascade)
{
if (file_exists($_ci_view_file.$_ci_file))
{
$_ci_path = $_ci_view_file.$_ci_file;
$file_exists = TRUE;
break;
}
if ( ! $cascade)
{
break;
}
}
}
if ( ! $file_exists && ! file_exists($_ci_path))
{
throw new Exception('View file '.$view.' doesn\'t exist.');
}
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return));
}
}
它現在拋出一個異常 - 你唯一需要做的 - 就是抓住它
try
{
$file = "login";
$this->load->view($file, array(),true);
}
catch(\Throwable $e)
{
echo $e->getMessage();
}
如果您使用 PHP < 7 您需要捕獲異常而不是 Throwable 接口。
嘗試
if(! file_exists(APPPATH."views"."/$foldername/$filename.php") )
redirect(base_url()); //or anything you want
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.