if(file_exists($RequiredFile)){require_once($RequiredFile);}else{die('Error: File Does Not Exist');}
因为当require_once杀死页面时,它有时会回显您网站文件的目录
这是我为需要文件而创建的自定义函数:
function addFile($file, $type = 'php', $important=false){//site-content is a directory where I store all the files that I plan to require_once//the site-content directory has "deny from all" in its .htaccess file to block direct connectionsif($type && file_exists('site-content/'.$file.'.'.$type) && !is_dir('site-content/'.$file.'.'.$type)){//!is_dir checks that the file is not a folderrequire_once('site-content/'.$file.'.'.$type);return 'site-content/'.$file.'.'.$type;}else if(!$type && file_exists('site-content/'.$file) && !is_dir('site-content/'.$file)){//if you set "$type=false" you can add the file type (.php, .ect) to the end of the "$file" (useful for requiring files named after changing vars)require_once('site-content/'.$file);return 'site-content/'.$file;}else if($important){//if you set $important to true, the function will kill the page (which also prevents accidentally echoing the main directory path of the server)die('Server Error: Files Missing');return false;}else{//the function returns false if the file does not exist, so you can check if your functions were successfully addedreturn false;}}
<?php//my site configuration file
//For Database$location='localhost';$dbuser='yourname';$userpw='yourpassword';$database='nameofdatabase';?>
还有一个具有使用数据库的静态函数的类:
<?phpclass UsedInLoop {public static function databaseQuery(){require(/path/to/conf.php); //require_once will not work here$db = new mysqli($location, $dbuser, $userpw, $database);//yada yada yada}}?>
并且该静态函数在循环内迭代调用的另一个函数中使用:
<?phprequire_once('path/to/arbitraryObject.php'); //either will likely be OK at this level$obj = new arbitraryObject();foreach($array as $element){$obj->myFunction();}?>
<?phpclass arbitraryObject {public function myFunction(){require_once(/path/to/UsedInLoop.php); //This must be require_once. require() will not workUsedInLoop::databaseQuery();}}?>
当然,将其移出函数可以解决这个问题:
<?phprequire(/path/to/UsedInLoop.php); //now require() is fineclass arbitraryObject {public function myFunction(){UsedInLoop::databaseQuery();}}?>