原文来自http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/ 1.不要使用相对路径 常常会看到: require_once('../../lib/some_class.php'); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录. 因此会检查过多路径.
原文来自http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/
1.不要使用相对路径
require_once('../../lib/some_class.php');
view sourceprint? define('ROOT' , '/var/www/project/'); require_once(ROOT . '../../lib/some_class.php'); //rest of the code
我们定义了一个绝对路径, 值被写死了. 我们还可以改进它. 路径 /var/www/project 也可能会改变, 那么我们每次都要改变它吗? 不是的, 我们可以使用__FILE__常量, 如:
//suppose your script is /var/www/project/index.php //Then __FILE__ will always have that full path. define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME)); require_once(ROOT . '../../lib/some_class.php'); //rest of the code
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'); require_once( $path ); } load_class('Database'); load_class('Mail');
function load_class($class_name) { //path to the class file $path = ROOT . '/lib/' . $class_name . '.php'); if(file_exists($path)) { require_once( $path ); } }
define('ENVIRONMENT' , 'development'); if(! $db->query( $query ) { if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }
define('ENVIRONMENT' , 'production'); if(! $db->query( $query ) { if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }
/** Method to execute a command in the terminal Uses : 1. system 2. passthru 3. exec 4. shell_exec */ function terminal($command) { //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("\n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var); } terminal('ls');
function add_to_cart($item_id , $qty) { $_SESSION['cart']['item_id'] = $qty; } add_to_cart( 'IPHONE3' , 2 );
function add_to_cart($item_id , $qty) { if(!is_array($item_id)) { $_SESSION['cart']['item_id'] = $qty; } else { foreach($item_id as $i_id => $qty) { $_SESSION['cart']['i_id'] = $qty; } } } add_to_cart( 'IPHONE3' , 2 ); add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );
<?php echo "Hello"; //Now dont close this tag
<?php class super_class { function super_function() { //super code } } ?> //super extra character after the closing tag index.php
require_once('super_class.php'); //echo an image or pdf , or set the cookies or session data
<?php class super_class { function super_function() { //super code } } //No closing tag
function print_header() { echo "<div id="header">Site Log and Login links</div>"; } function print_footer() { echo "<div id="footer">Site was made by me</div>"; } print_header(); for($i = 0 ; $i 替代方案, 在某地方集中收集输出. 你可以存储在函数的局部变量中, 也可以使用ob_start和ob_end_clean. 如下:<br> <pre class="brush:php;toolbar:false">function print_header() { $o = "<div id="header">Site Log and Login links</div>"; return $o; } function print_footer() { $o = "<div id="footer">Site was made by me</div>"; return $o; } echo print_header(); for($i = 0 ; $i <br> 为什么需要输出缓冲:<br> >>可以在发送给浏览器前更改输出. 如 str_replaces 函数或可能是 preg_replaces 或添加些监控/调试的html内容.<br> >>输出给浏览器的同时又做php的处理很糟糕. 你应该看到过有些站点的侧边栏或中间出现错误信息. 知道为什么会发生吗? 因为处理和输出混合了.<br> 8. 发送正确的mime类型头信息, 如果输出非html内容的话.<br> 输出一些xml.<pre class="brush:php;toolbar:false">$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'; $xml = "<response> <code>0</code> </response>"; //Send xml data echo $xml;
$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'; $xml = "<response> <code>0</code> </response>"; //Send xml data header("content-type: text/xml"); echo $xml;
JavaScript header("content-type: application/x-javascript"); echo "var a = 10"; CSS header("content-type: text/css"); echo "#div id { background:#000; }";
//Attempt to connect to database $c = mysqli_connect($this->host , $this->username, $this->password); //Check connection validity if (!$c) { die ("Could not connect to the database host: ". mysqli_connect_error()); } //Set the character set of the connection if(!mysqli_set_charset ( $c , 'UTF8' )) { die('mysqli_set_charset() failed'); }
$value = htmlentities($this->value , ENT_QUOTES , CHARSET);
$images = array( 'myself.png' , 'friends.png' , 'colleagues.png' ); $js_code = ''; foreach($images as $image) { $js_code .= "'$image' ,"; } $js_code = 'var images = [' . $js_code . ']; '; echo $js_code; //Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];
$images = array( 'myself.png' , 'friends.png' , 'colleagues.png' ); $js_code = 'var images = ' . json_encode($images); echo $js_code; //Output is : var images = ["myself.png","friends.png","colleagues.png"]
$contents = "All the content"; $file_path = "/var/www/project/content.txt"; file_put_contents($file_path , $contents);
$contents = "All the content"; $dir = '/var/www/project'; $file_path = $dir . "/content.txt"; if(is_writable($dir)) { file_put_contents($file_path , $contents); } else { die("Directory $dir is not writable, or does not exist. Please check"); }
// Read and write for owner, read for everybody else chmod("/somedir/somefile", 0644); // Everything for owner, read and execute for others chmod("/somedir/somefile", 0755);
if($_POST['submit'] == 'Save') { //Save the things }
if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ) { //Save the things }
//Delay for some time function delay() { $sync_delay = get_option('sync_delay'); echo "Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done "; }
//Delay for some time function delay() { static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done "; }
$_SESSION['username'] = $username; $username = $_SESSION['username'];
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; }
function utility_a() { //This function does a utility thing like string processing } function utility_b() { //This function does nother utility thing like database processing } function utility_c() { //This function is ... }
class Utility { public static function utility_a() { } public static function utility_b() { } public static function utility_c() { } }
//and call them as $a = Utility::utility_a(); $b = Utility::utility_b();
if($a == true) { $a_count++; }
foreach($arr as $c => $v) { $arr[$c] = trim($v); }
$amount = intval( $_GET['amount'] ); $rate = (int) $_GET['rate'];
$db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB $cc = $db_records_in_array_format; //2MB more some_function($cc); //Another 2MB ?
$a = get_large_array(); pass_to_function(&$a);
class A { function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a } }
function add_to_cart() { $db = new Database(); $db->query("INSERT INTO cart ....."); } function empty_cart() { $db = new Database(); $db->query("DELETE FROM cart ....."); }
$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')"; $db->query($query); //call to mysqli_query()
function insert_record($table_name , $data) { foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'" . implode("','" , array_values($data)) . "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query); } $data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone); insert_record('users' , $data);
<base href="http://www.domain.com/store/"> <img src="happy.jpg" alt="提高PHP代码质量的36个技巧" >