php优化

1.include/require使用绝对路径,不使用相对路径

require_once('../../lib/some_class.php');

原因有二:会查找很多目录,搜索文件

             如果当前文件,被其他不同目录路径的文件包含的时候。当前文件的路径会变为包含文件的路径

define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
require_once(ROOT . '../../lib/some_class.php');

2.封装load方法代替require

require_once('lib/Database.php');
require_once('lib/Mail.php');
 
require_once('helpers/utitlity_functions.php');
function load_class($class_name)
	{
	    //path to the class file
	    $path = ROOT . '/lib/' . $class_name . '.php');
	     
	    if(file_exists($path))
	    {
	        require_once( $path );
	    }
	}
load_class('Database');
load_class('Mail');
3.开启debug方便调试

define('ENVIRONMENT' , 'development');
	 
	if(! $db->query( $query )
	{
	    if(ENVIRONMENT == 'development')
	    {
	        echo "$query failed";
	    }
	    else
	    {
	        echo "Database error. Please contact administrator";
	    }   
	}
4.写文件之前,判断目录是否可写,是否存在

$contents = "All the content";
$dir = '/var/www/project';
$file_path = $dir . "/content.txt";

if(ids_dir($dir)) {
     die('dir is not exist');
}
if(is_writable($dir))
{
    file_put_contents($file_path , $contents);
}
else
{
    die("Directory $dir is not writable, or does not exist. Please check");
}
5。不要直接使用赋值session ,同一个域下容易被覆盖

define('APP_ID' , 'abc_corp_ecommerce');
	 
	//Function to get a session variable
	function session_get($key)
	{
	    $k = APP_ID . '.' . $key;
	    
	    if(isset($_SESSION[$k]))
	    {
	        return $_SESSION[$k];
	    }
	     
	    return false;
	}
	 
	//Function set the session variable
	function session_set($key , $value)
	{
	    $k = APP_ID . '.' . $key;
	    $_SESSION[$k] = $value;
	     
	    return true;
	}



你可能感兴趣的:(php优化)