原文来自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 < 100; $i++) { echo "I is : $i '; } print_footer();替代方案, 在某地方集中收集输出. 你可以存储在函数的局部变量中, 也可以使用ob_start和ob_end_clean. 如下:
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 < 100; $i++) { echo "I is : $i '; } echo print_footer();
$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;注意header行. 该行告知浏览器发送的是xml类型的内容. 所以浏览器能正确的处理. 很多的javascript库也依赖头信息.
JavaScript header("content-type: application/x-javascript"); echo "var a = 10"; CSS header("content-type: text/css"); echo "#div id { background:#000; }";9. 为mysql连接设置正确的字符编码
//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'); }一旦连接数据库, 最好设置连接的 characterset. 你的应用如果要支持多语言, 这么做是必须的.
$value = htmlentities($this->value , ENT_QUOTES , CHARSET);php5.4以后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍然要留意编码问题,.
$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);这大体上正确. 但有些间接的问题. file_put_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);15. 不要依赖submit按钮值来检查表单提交行为
if($_POST['submit'] == 'Save') { //Save the things }上面大多数情况正确, 除了应用是多语言的. ‘Save’ 可能代表其它含义. 你怎么区分它们呢. 因此, 不要依赖于submit按钮的值.
if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ) { //Save the things }现在你从submit按钮值中解脱出来了.
//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 "; }17. 不要直接使用 $_SESSION 变量
$_SESSION['username'] = $username; $username = $_SESSION['username'];这会导致某些问题. 如果在同个域名中运行了多个应用, session 变量可能会冲突. 两个不同的应用可能使用同一个session key. 例如, 一个前端门户, 和一个后台管理系统使用同一域名.
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; }18. 將工具函数封装到类中
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();显而易见的好处是, 如果php内建有同名的函数, 这样可以避免冲突.
if($a == true) { $a_count++; }不要尝试省略一些语法来缩短代码. 而是让你的逻辑简短.
foreach($arr as $c => $v) { $arr[$c] = trim($v); }但使用 array_map 更简单:
$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);
<head> <base href="http://www.domain.com/store/"> </head> <body> <img src="happy.jpg" /> </body> </html>
<a href="../home.php">Home</a> <a href="ipad.php">Ipad</a>
<head> <base href="http://www.domain.com/store/"> </head> <body> <a href="home.php">Home</a> <a href="products/ipad.php">Ipad</a> </body> </html>
ini_set('display_errors', 1); error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);
$ php -a Interactive shell php > echo strtotime("0000-00-00 00:00:00"); -62170005200 php > echo strtotime('1000-01-30'); -30607739600 php > echo strtotime('2100-01-30'); 4104930600
set_time_limit(30); //Rest of the code