A-A+

提高php代码质量 36计

2012年10月09日 学习小计 暂无评论 阅读 1 次

girl laptop

1.不要使用相对路径

常常会看到:

 

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

 

该方法有很多缺点:

它首先查找指定的php包含路径, 然后查找当前目录.

因此会检查过多路径.

如果该脚本被另一目录的脚本包含, 它的基本目录变成了另一脚本所在的目录.

另一问题, 当定时任务运行该脚本, 它的上级目录可能就不是工作目录了.

因此最佳选择是使用绝对路径:

 

1 define('ROOT' , '/var/www/project/');
2 require_once(ROOT . '../../lib/some_class.php');
3   
4 //rest of the code

 

 

 我们定义了一个绝对路径, 值被写死了. 我们还可以改进它. 路径 /var/www/project 也可能会改变, 那么我们每次都要改变它吗? 不是的, 我们可以使用__FILE__常量, 如:

 

1 //suppose your script is /var/www/project/index.php
2 //Then __FILE__ will always have that full path.
3   
4 define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
5 require_once(ROOT . '../../lib/some_class.php');
6   
7 //rest of the code

 

现在, 无论你移到哪个目录, 如移到一个外网的服务器上, 代码无须更改便可正确运行.

2. 不要直接使用 require, include, include_once, required_once

可以在脚本头部引入多个文件, 像类库, 工具文件和助手函数等, 如:

 

1 require_once('lib/Database.php');
2 require_once('lib/Mail.php');
3   
4 require_once('helpers/utitlity_functions.php');

 

这种用法相当原始. 应该更灵活点. 应编写个助手函数包含文件. 例如:

 

1 function load_class($class_name)
2 {
3     //path to the class file
4     $path = ROOT . '/lib/' . $class_name . '.php');
5     require_once( $path );
6 }
7   
8 load_class('Database');
9 load_class('Mail');

 

有什么不一样吗? 该代码更具可读性.

將来你可以按需扩展该函数, 如:

 

01 function load_class($class_name)
02 {
03     //path to the class file
04     $path = ROOT . '/lib/' . $class_name . '.php');
05   
06     if(file_exists($path))
07     {
08         require_once( $path );
09     }
10 }

 

还可做得更多:

为同样文件查找多个目录

能很容易的改变放置类文件的目录, 无须在代码各处一一修改

可使用类似的函数加载文件, 如html内容.

3. 为应用保留调试代码

在开发环境中, 我们打印数据库查询语句, 转存有问题的变量值, 而一旦问题解决, 我们注释或删除它们. 然而更好的做法是保留调试代码.

在开发环境中, 你可以:

 

01 define('ENVIRONMENT' , 'development');
02   
03 if(! $db->query( $query )
04 {
05     if(ENVIRONMENT == 'development')
06     {
07         echo "$query failed";
08     }
09     else
10     {
11         echo "Database error. Please contact administrator";
12     }
13 }

 

在服务器中, 你可以:

 

01 define('ENVIRONMENT' , 'production');
02   
03 if(! $db->query( $query )
04 {
05     if(ENVIRONMENT == 'development')
06     {
07         echo "$query failed";
08     }
09     else
10     {
11         echo "Database error. Please contact administrator";
12     }
13 }

 

4. 使用可跨平台的函数执行命令

system, exec, passthru, shell_exec 这4个函数可用于执行系统命令. 每个的行为都有细微差别. 问题在于, 当在共享主机中, 某些函数可能被选择性的禁用. 大多数新手趋于每次首先检查哪个函数可用, 然而再使用它.

更好的方案是封成函数一个可跨平台的函数. 

 

01 /**
02     Method to execute a command in the terminal
03     Uses :
04   
05     1. system
06     2. passthru
07     3. exec
08     4. shell_exec
09   
10 */
11 function terminal($command)
12 {
13     //system
14     if(function_exists('system'))
15     {
16         ob_start();
17         system($command , $return_var);
18         $output = ob_get_contents();
19         ob_end_clean();
20     }
21     //passthru
22     else if(function_exists('passthru'))
23     {
24         ob_start();
25         passthru($command , $return_var);
26         $output = ob_get_contents();
27         ob_end_clean();
28     }
29   
30     //exec
31     else if(function_exists('exec'))
32     {
33         exec($command , $output , $return_var);
34         $output = implode("n" , $output);
35     }
36   
37     //shell_exec
38     else if(function_exists('shell_exec'))
39     {
40         $output = shell_exec($command) ;
41     }
42   
43     else
44     {
45         $output = 'Command execution not possible on this system';
46         $return_var = 1;
47     }
48   
49     return array('output' => $output , 'status' => $return_var);
50 }
51   
52 terminal('ls');

 

上面的函数將运行shell命令, 只要有一个系统函数可用, 这保持了代码的一致性. 

5. 灵活编写函数

 

1 function add_to_cart($item_id , $qty)
2 {
3     $_SESSION['cart']['item_id'] = $qty;
4 }
5   
6 add_to_cart( 'IPHONE3' , 2 );

 

使用上面的函数添加单个项目. 而当添加项列表的时候,你要创建另一个函数吗? 不用, 只要稍加留意不同类型的参数, 就会更灵活. 如:

 

01 function add_to_cart($item_id , $qty)
02 {
03     if(!is_array($item_id))
04     {
05         $_SESSION['cart']['item_id'] = $qty;
06     }
07   
08     else
09     {
10         foreach($item_id as $i_id => $qty)
11         {
12             $_SESSION['cart']['i_id'] = $qty;
13         }
14     }
15 }
16   
17 add_to_cart( 'IPHONE3' , 2 );
18 add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );

 

现在, 同个函数可以处理不同类型的输入参数了. 可以参照上面的例子重构你的多处代码, 使其更智能.

6. 有意忽略php关闭标签

我很想知道为什么这么多关于php建议的博客文章都没提到这点.

 

1 <?php
2   
3 echo "Hello";
4   
5 //Now dont close this tag

 

这將节约你很多时间. 我们举个例子: 

一个 super_class.php 文件

 

01 <?php
02 class super_class
03 {
04     function super_function()
05     {
06         //super code
07     }
08 }
09 ?>
10 //super extra character after the closing tag

 

index.php 

 

1 require_once('super_class.php');
2   
3 //echo an image or pdf , or set the cookies or session data

 

这样, 你將会得到一个 Headers already send error. 为什么? 因为 “super extra character” 已经被输出了. 现在你得开始调试啦. 这会花费大量时间寻找 super extra 的位置.

因此, 养成省略关闭符的习惯:

 

01 <?php
02 class super_class
03 {
04     function super_function()
05     {
06         //super code
07     }
08 }
09   
10 //No closing tag

 

这会更好.  

 

7. 在某地方收集所有输入, 一次输出给浏览器

这称为输出缓冲, 假如说你已在不同的函数输出内容:

 

01 function print_header()
02 {
03     echo "<div id='header'>Site Log and Login links</div>";
04 }
05   
06 function print_footer()
07 {
08     echo "<div id='footer'>Site was made by me</div>";
09 }
10   
11 print_header();
12 for($i = 0 ; $i < 100; $i++)
13 {
14     echo "I is : $i <br />';
15 }
16 print_footer();

 

替代方案, 在某地方集中收集输出. 你可以存储在函数的局部变量中, 也可以使用ob_start和ob_end_clean. 如下:

 

01 function print_header()
02 {
03     $o = "<div id='header'>Site Log and Login links</div>";
04     return $o;
05 }
06   
07 function print_footer()
08 {
09     $o = "<div id='footer'>Site was made by me</div>";
10     return $o;
11 }
12   
13 echo print_header();
14 for($i = 0 ; $i < 100; $i++)
15 {
16     echo "I is : $i <br />';
17 }
18 echo print_footer();

 

为什么需要输出缓冲:

>>可以在发送给浏览器前更改输出. 如 str_replaces 函数或可能是 preg_replaces 或添加些监控/调试的html内容.

>>输出给浏览器的同时又做php的处理很糟糕. 你应该看到过有些站点的侧边栏或中间出现错误信息. 知道为什么会发生吗? 因为处理和输出混合了.

8. 发送正确的mime类型头信息, 如果输出非html内容的话.

输出一些xml.

 

1 $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
2 $xml = "<response>
3   <code>0</code>
4 </response>";
5   
6 //Send xml data
7 echo $xml;

 

工作得不错. 但需要一些改进.

 

1 $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
2 $xml = "<response>
3   <code>0</code>
4 </response>";
5   
6 //Send xml data
7 header("content-type: text/xml");
8 echo $xml;

 

注意header行. 该行告知浏览器发送的是xml类型的内容. 所以浏览器能正确的处理. 很多的javascript库也依赖头信息.

类似的有 javascript , css, jpg image, png image:

JavaScript

 

1 header("content-type: application/x-javascript");
2 echo "var a = 10";

 

CSS

 

1 header("content-type: text/css");
2 echo "#div id { background:#000; }";

 

9. 为mysql连接设置正确的字符编码

曾经遇到过在mysql表中设置了unicode/utf-8编码,  phpadmin也能正确显示, 但当你获取内容并在页面输出的时候,会出现乱码. 这里的问题出在mysql连接的字符编码.

 

01 //Attempt to connect to database
02 $c = mysqli_connect($this->host , $this->username, $this->password);
03   
04 //Check connection validity
05 if (!$c)&nbsp;
06 {
07     die ("Could not connect to the database host: <br />". mysqli_connect_error());
08 }
09   
10 //Set the character set of the connection
11 if(!mysqli_set_charset ( $c , 'UTF8' ))
12 {
13     die('mysqli_set_charset() failed');
14 }

 

一旦连接数据库, 最好设置连接的 characterset. 你的应用如果要支持多语言, 这么做是必须的.

10. 使用 htmlentities 设置正确的编码选项

php5.4前, 字符的默认编码是ISO-8859-1, 不能直接输出如À â等.

 

1 $value = htmlentities($this->value , ENT_QUOTES , CHARSET);

 

php5.4以后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍然要留意编码问题,.

11. 不要在应用中使用gzip压缩输出, 让apache处理

考虑过使用 ob_gzhandler 吗? 不要那样做. 毫无意义. php只应用来编写应用. 不应操心服务器和浏览器的数据传输优化问题.

使用apache的mod_gzip/mod_deflate 模块压缩内容.

12. 使用json_encode输出动态javascript内容

时常会用php输出动态javascript内容:

 

01 $images = array(
02  'myself.png' , 'friends.png' , 'colleagues.png'
03 );
04   
05 $js_code = '';
06   
07 foreach($images as $image)
08 {
09 $js_code .= "'$image' ,";
10 }
11   
12 $js_code = 'var images = [' . $js_code . ']; ';
13   
14 echo $js_code;
15   
16 //Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];

 

更聪明的做法, 使用 json_encode:

 

1 $images = array(
2  'myself.png' , 'friends.png' , 'colleagues.png'
3 );
4   
5 $js_code = 'var images = ' . json_encode($images);
6   
7 echo $js_code;
8   
9 //Output is : var images = ["myself.png","friends.png","colleagues.png"]

 

优雅乎?

13. 写文件前, 检查目录写权限

写或保存文件前, 确保目录是可写的, 假如不可写, 输出错误信息. 这会节约你很多调试时间. linux系统中, 需要处理权限, 目录权限不当会导致很多很多的问题, 文件也有可能无法读取等等.

确保你的应用足够智能, 输出某些重要信息.

 

1 $contents = "All the content";
2 $file_path = "/var/www/project/content.txt";
3   
4 file_put_contents($file_path , $contents);

 

这大体上正确. 但有些间接的问题. file_put_contents 可能会由于几个原因失败:

>>父目录不存在

>>目录存在, 但不可写

>>文件被写锁住?

所以写文件前做明确的检查更好.

 

01 $contents = "All the content";
02 $dir = '/var/www/project';
03 $file_path = $dir . "/content.txt";
04   
05 if(is_writable($dir))
06 {
07     file_put_contents($file_path , $contents);
08 }
09 else
10 {
11     die("Directory $dir is not writable, or does not exist. Please check");
12 }

 

这么做后, 你会得到一个文件在何处写及为什么失败的明确信息.

14. 更改应用创建的文件权限

在linux环境中, 权限问题可能会浪费你很多时间. 从今往后, 无论何时, 当你创建一些文件后, 确保使用chmod设置正确权限. 否则的话, 可能文件先是由"php"用户创建, 但你用其它的用户登录工作, 系统將会拒绝访问或打开文件, 你不得不奋力获取root权限,  更改文件的权限等等.

 

1 // Read and write for owner, read for everybody else
2 chmod("/somedir/somefile", 0644);
3   
4 // Everything for owner, read and execute for others
5 chmod("/somedir/somefile", 0755);

 

15. 不要依赖submit按钮值来检查表单提交行为

 

1 if($_POST['submit'] == 'Save')
2 {
3     //Save the things
4 }

 

上面大多数情况正确, 除了应用是多语言的. 'Save' 可能代表其它含义. 你怎么区分它们呢. 因此, 不要依赖于submit按钮的值.

 

1 if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )
2 {
3     //Save the things
4 }

 

现在你从submit按钮值中解脱出来了.

16. 为函数内总具有相同值的变量定义成静态变量

 

1 //Delay for some time
2 function delay()
3 {
4     $sync_delay = get_option('sync_delay');
5   
6     echo "<br />Delaying for $sync_delay seconds...";
7     sleep($sync_delay);
8     echo "Done <br />";
9 }

 

用静态变量取代:

 

01 //Delay for some time
02 function delay()
03 {
04     static $sync_delay = null;
05   
06     if($sync_delay == null)
07     {
08     $sync_delay = get_option('sync_delay');
09     }
10   
11     echo "<br />Delaying for $sync_delay seconds...";
12     sleep($sync_delay);
13     echo "Done <br />";
14 }

 

17. 不要直接使用 $_SESSION 变量

某些简单例子:

 

1 $_SESSION['username'] = $username;
2 $username = $_SESSION['username'];

 

这会导致某些问题. 如果在同个域名中运行了多个应用, session 变量可能会冲突. 两个不同的应用可能使用同一个session key. 例如, 一个前端门户, 和一个后台管理系统使用同一域名.

从现在开始, 使用应用相关的key和一个包装函数:

 

01 define('APP_ID' , 'abc_corp_ecommerce');
02   
03 //Function to get a session variable
04 function session_get($key)
05 {
06     $k = APP_ID . '.' . $key;
07   
08     if(isset($_SESSION[$k]))
09     {
10         return $_SESSION[$k];
11     }
12   
13     return false;
14 }
15   
16 //Function set the session variable
17 function session_set($key , $value)
18 {
19     $k = APP_ID . '.' . $key;
20     $_SESSION[$k] = $value;
21   
22     return true;
23 }

 

18. 將工具函数封装到类中

假如你在某文件中定义了很多工具函数:

 

01 function utility_a()
02 {
03     //This function does a utility thing like string processing
04 }
05   
06 function utility_b()
07 {
08     //This function does nother utility thing like database processing
09 }
10   
11 function utility_c()
12 {
13     //This function is ...
14 }

 

这些函数的使用分散到应用各处. 你可能想將他们封装到某个类中:

 

01 class Utility
02 {
03     public static function utility_a()
04     {
05   
06     }
07   
08     public static function utility_b()
09     {
10   
11     }
12   
13     public static function utility_c()
14     {
15   
16     }
17 }
18   
19 //and call them as 
20   
21 $a = Utility::utility_a();
22 $b = Utility::utility_b();

 

显而易见的好处是, 如果php内建有同名的函数, 这样可以避免冲突.

另一种看法是, 你可以在同个应用中为同个类维护多个版本, 而不导致冲突. 这是封装的基本好处, 无它.

19. Bunch of silly tips 

>>使用echo取代print

>>使用str_replace取代preg_replace, 除非你绝对需要

>>不要使用 short tag

>>简单字符串用单引号取代双引号

>>head重定向后记得使用exit

>>不要在循环中调用函数

>>isset比strlen快

>>始中如一的格式化代码

>>不要删除循环或者if-else的括号

不要这样写代码:

 

1 <SPAN style="FONT-FAMILY: ''Helvetica, Arial, sans-serif''; COLOR: #333333">if($a == true) $a_count++;</SPAN>

 

这绝对WASTE.

写成:

 

1 <SPAN style="FONT-FAMILY: ''Helvetica, Arial, sans-serif''; COLOR: #333333">if($a == true)
2 {
3     $a_count++;
4 }</SPAN>

 

不要尝试省略一些语法来缩短代码. 而是让你的逻辑简短.

>>使用有高亮语法显示的文本编辑器. 高亮语法能让你减少错误.

 

20. 使用array_map快速处理数组

比如说你想 trim 数组中的所有元素. 新手可能会:

 

1 foreach($arr as $c => $v)
2 {
3     $arr[$c] = trim($v);
4 }

 

但使用 array_map 更简单:

1 $arr = array_map('trim' , $arr);

这会为$arr数组的每个元素都申请调用trim. 另一个类似的函数是 array_walk. 请查阅文档学习更多技巧.

21. 使用 php filter 验证数据

你肯定曾使用过正则表达式验证 email , ip地址等. 是的,每个人都这么使用. 现在, 我们想做不同的尝试, 称为filter.

php的filter扩展提供了简单的方式验证和检查输入.

22. 强制类型检查

 

1 $amount = intval( $_GET['amount'] );
2 $rate = (int) $_GET['rate'];

 

这是个好习惯.

23. 如果需要,使用profiler如xdebug

如果你使用php开发大型的应用, php承担了很多运算量, 速度会是一个很重要的指标. 使用profile帮助优化代码. 可使用

xdebug和webgrid.

24. 小心处理大数组

对于大的数组和字符串, 必须小心处理. 常见错误是发生数组拷贝导致内存溢出,抛出Fatal Error of Memory size 信息:

 

1 $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
2   
3 $cc = $db_records_in_array_format; //2MB more
4   
5 some_function($cc); //Another 2MB ?

 

当导入或导出csv文件时, 常常会这么做.

不要认为上面的代码会经常因内存限制导致脚本崩溃. 对于小的变量是没问题的, 但处理大数组的时候就必须避免.

确保通过引用传递, 或存储在类变量中:

 

1 $a = get_large_array();
2 pass_to_function(&$a);

 

这么做后, 向函数传递变量引用(而不是拷贝数组). 查看文档.

 

01 class A
02 {
03     function first()
04     {
05         $this->a = get_large_array();
06         $this->pass_to_function();
07     }
08   
09     function pass_to_function()
10     {
11         //process $this->a
12     }
13 }

 

尽快的 unset 它们, 让内存得以释放,减轻脚本负担.

25.  由始至终使用单一数据库连接

确保你的脚本由始至终都使用单一的数据库连接. 在开始处正确的打开连接, 使用它直到结束, 最后关闭它. 不要像下面这样在函数中打开连接:

 

01 function add_to_cart()
02 {
03     $db = new Database();
04     $db->query("INSERT INTO cart .....");
05 }
06   
07 function empty_cart()
08 {
09     $db = new Database();
10     $db->query("DELETE FROM cart .....");
11 }

 

 

使用多个连接是个糟糕的, 它们会拖慢应用, 因为创建连接需要时间和占用内存.

特定情况使用单例模式, 如数据库连接.

26. 避免直接写SQL, 抽象之

不厌其烦的写了太多如下的语句:

 

1 <SPAN style="FONT-FAMILY: ''Helvetica, Arial, sans-serif''; COLOR: #333333">$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";
2 $db->query($query); //call to mysqli_query()</SPAN>

 

这不是个建壮的方案. 它有些缺点:

>>每次都手动转义值

>>验证查询是否正确

>>查询的错误会花很长时间识别(除非每次都用if-else检查)

>>很难维护复杂的查询

因此使用函数封装:

 

01 <SPAN style="FONT-FAMILY: ''Helvetica, Arial, sans-serif''; COLOR: #333333">function insert_record($table_name , $data)
02 {
03     foreach($data as $key => $value)
04     {
05     //mysqli_real_escape_string
06         $data[$key] = $db->mres($value);
07     }
08   
09     $fields = implode(',' , array_keys($data));
10     $values = "'" . implode("','" , array_values($data)) . "'";
11   
12     //Final query
13     $query = "INSERT INTO {$table}($fields) VALUES($values)";
14   
15     return $db->query($query);
16 }
17   
18 $data = array('name' => $name , 'email' => $email  , 'address' => $address , 'phone' => $phone);
19   
20 insert_record('users' , $data);</SPAN>

 

看到了吗? 这样会更易读和扩展. record_data 函数小心的处理了转义. 

最大的优点是数据被预处理为一个数组, 任何语法错误都会被捕获.

该函数应该定义在某个database类中, 你可以像 $db->insert_record这样调用.

查看本文, 看看怎样让你处理数据库更容易.

类似的也可以编写update,select,delete方法. 试试吧.

27. 將数据库生成的内容缓存到静态文件中

如果所有的内容都是从数据库获取的, 它们应该被缓存. 一旦生成了, 就將它们保存在临时文件中. 下次请求该页面时, 可直接从缓存中取, 不用再查数据库.

好处:

>>节约php处理页面的时间, 执行更快

>>更少的数据库查询意味着更少的mysql连接开销

28. 在数据库中保存session

基于文件的session策略会有很多限制. 使用基于文件的session不能扩展到集群中, 因为session保存在单个服务器中. 但数据库可被多个服务器访问, 这样就可以解决问题.

在数据库中保存session数据, 还有更多好处:

>>处理username重复登录问题. 同个username不能在两个地方同时登录.

>>能更准备的查询在线用户状态.

29. 避免使用全局变量

>>使用 defines/constants

>>使用函数获取值

>>使用类并通过$this访问

30. 在head中使用base标签

没听说过? 请看下面:

 

1 <head>
2 <base href="http://www.domain.com/store/">
3 </head>
4 <body>
5 <img src="happy.jpg" />
6 </body>
7 </html>

 

base 标签非常有用. 假设你的应用分成几个子目录, 它们都要包括相同的导航菜单.

www.domain.com/store/home.php

www.domain.com/store/products/ipad.php

在首页中, 可以写:

 

1 <a href="home.php">Home</a>
2 <a href="products/ipad.php">Ipad</a>

 

但在你的ipad.php不得不写成:

 

1 <SPAN style="FONT-FAMILY: ''Helvetica, Arial, sans-serif''; COLOR: #333333"><a href="../home.php">Home</a>
2 <a href="ipad.php">Ipad</a></SPAN>

 

因为目录不一样. 有这么多不同版本的导航菜单要维护, 很糟糕啊. 

因此, 请使用base标签.

 

1 <SPAN style="FONT-FAMILY: ''Helvetica, Arial, sans-serif''; COLOR: #333333"><head>
2 <base href="http://www.domain.com/store/">
3 </head>
4 <body>
5 <a href="home.php">Home</a>
6 <a href="products/ipad.php">Ipad</a>
7 </body>
8 </html></SPAN>

 

现在, 这段代码放在应用的各个目录文件中行为都一致. 

31. 永远不要將 error_reporting 设为 0

关闭不相的错误报告. E_FATAL 错误是很重要的. 

 

1 <SPAN style="FONT-FAMILY: 'Helvetica, Arial, sans-serif'; COLOR: #333333">ini_set('display_errors', 1);
2 error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);</SPAN>

 

32. 注意平台体系结构

integer在32位和64位体系结构中长度是不同的. 因此某些函数如 strtotime 的行为会不同.

在64位的机器中, 你会看到如下的输出.

 

1 <SPAN style="FONT-FAMILY: ''Helvetica, Arial, sans-serif''; COLOR: #333333">$ php -a
2 Interactive shell
3   
4 php > echo strtotime("0000-00-00 00:00:00");
5 -62170005200
6 php > echo strtotime('1000-01-30');
7 -30607739600
8 php > echo strtotime('2100-01-30');
9 4104930600</SPAN>

 

但在32位机器中, 它们將是bool(false). 查看这里, 了解更多.

33. 不要过分依赖 set_time_limit

如果你想限制最小时间, 可以使用下面的脚本:

 

1 <SPAN style="FONT-FAMILY: ''Helvetica, Arial, sans-serif''; COLOR: #333333">set_time_limit(30);
2   
3 //Rest of the code</SPAN>

 

高枕无忧吗?  注意任何外部的执行, 如系统调用,socket操作, 数据库操作等, 就不在set_time_limits的控制之下.

 因此, 就算数据库花费了很多时间查询, 脚本也不会停止执行. 视情况而定.

34. 使用扩展库

一些例子:

>>mPDF -- 能通过html生成pdf文档

>>PHPExcel -- 读写excel

>>PhpMailer -- 轻松处理发送包含附近的邮件

>>pChart -- 使用php生成报表

使用开源库完成复杂任务, 如生成pdf, ms-excel文件, 报表等.

35. 使用MVC框架

是时候使用像 codeigniter 这样的MVC框架了. MVC框架并不强迫你写面向对象的代码. 它们仅將php代码与html分离.

>>明确区分php和html代码. 在团队协作中有好处, 设计师和程序员可以同时工作.

>>面向对象设计的函数能让你更容易维护

>>内建函数完成了很多工作, 你不需要重复编写

>>开发大的应用是必须的

>>很多建议, 技巧和hack已被框架实现了

36. 时常看看 phpbench 

phpbench 提供了些php基本操作的基准测试结果, 它展示了一些徽小的语法变化是怎样导致巨大差异的.

查看php站点的评论, 有问题到IRC提问, 时常阅读开源代码, 使用Linux开发. 

OSCHINA原创翻译,转载请注明出处: OSCHINA

英文原文

 

The Techniques

1. Do not use relative paths , instead define a ROOT path

Its quite common to see such lines :

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

This approach has many drawbacks :

It first searches for directories specified in the include paths of php , then looks from the current directory.
So many directories are checked.

When a script is included by another script in a different directory , its base directory changes to that of the including script.

Another issue , is that when a script is being run from cron , it may not have its parent directory as the working directory.

So its a good idea to have absolute paths :

1 define('ROOT' , '/var/www/project/');
2 require_once(ROOT . '../../lib/some_class.php');
3   
4 //rest of the code

Now this is an absolute path and will always stay constant. But we can improve this further. The directory /var/www/project can change , so do we change it everytime ? No instead we make it portable using magic constants like __FILE__ . Take a closer look :

1 //suppose your script is /var/www/project/index.php
2 //Then __FILE__ will always have that full path.
3   
4 define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
5 require_once(ROOT . '../../lib/some_class.php');
6   
7 //rest of the code

So now even if you shift your project to a different directory , like moving it to an online server , the same code will run without any changes.

2. Dont use require , include , require_once or include_once

Your script could be including various files on top , like class libraries , files for utility and helper functions etc like this :

1 require_once('lib/Database.php');
2 require_once('lib/Mail.php');
3   
4 require_once('helpers/utitlity_functions.php');

This is rather primitive. The code needs to be more flexible. Write up helper functions to include things more easily. Lets take an example :

1 function load_class($class_name)
2 {
3     //path to the class file
4     $path = ROOT . '/lib/' . $class_name . '.php');
5     require_once( $path ); 
6 }
7   
8 load_class('Database');
9 load_class('Mail');

See any difference ? You must. It does not need any more explanation.
You can improve this further if you wish to like this :

1 function load_class($class_name)
2 {
3     //path to the class file
4     $path = ROOT . '/lib/' . $class_name . '.php');
5       
6     if(file_exists($path))
7     {
8         require_once( $path ); 
9     }
10 }

There are a lot of things that can be done with this :

Search multiple directories for the same class file.
Change the directory containing class files easily , without breaking the code anywhere.
Use similar functions for loading files that contain helper functions , html content etc.

3. Maintain debugging environment in your application

During development we echo database queries , dump variables which are creating problems , and then once the problem is solved , we comment them or erase them. But its a good idea to let everything stay and help in the long run

On your development machine you can do this :

1 define('ENVIRONMENT' , 'development');
2   
3 if(! $db->query( $query )
4 {
5     if(ENVIRONMENT == 'development')
6     {
7         echo "$query failed";
8     }
9     else
10     {
11         echo "Database error. Please contact administrator";
12     }    
13 }

And on the server you can do this :

1 define('ENVIRONMENT' , 'production');
2   
3 if(! $db->query( $query )
4 {
5     if(ENVIRONMENT == 'development')
6     {
7         echo "$query failed";
8     }
9     else
10     {
11         echo "Database error. Please contact administrator";
12     }    
13 }

4. Propagate status messages via session

Status messages are those messages that are generated after doing a task.

1 <?php
2 if($wrong_username || $wrong_password)
3 {
4     $msg = 'Invalid username or password';
5 }
6 ?>
7 <html>
8 <body>
9   
10 <?php echo $msg; ?>
11   
12 <form>
13 ...
14 </form>
15 </body>
16 </html>

Code like that is common. Using variables to show status messages has limitations. They cannot be send via redirects (unless you propagate them as GET variables to the next script , which is very silly). In large scripts there might be multiple messages etc.

Best way is to use session to propagate them (even if on same page). For this there has to be a session_start on every page.

1 function set_flash($msg)
2 {
3     $_SESSION['message'] = $msg;
4 }
5   
6 function get_flash()
7 {
8     $msg = $_SESSION['message'];
9     unset($_SESSION['message']);
10     return $msg;
11 }

and in your script :

1 <?php
2 if($wrong_username || $wrong_password)
3 {
4     set_flash('Invalid username or password');
5 }
6 ?>
7 <html>
8 <body>
9   
10 Status is : <?php echo get_flash(); ?>
11 <form>
12 ...
13 </form>
14 </body>
15 </html>

5. Make your functions flexible

1 function add_to_cart($item_id , $qty)
2 {
3     $_SESSION['cart'][$item_id] = $qty;
4 }
5   
6 add_to_cart( 'IPHONE3' , 2 );

When adding a single item you use the above function. When adding multiple items , will you create another function ? NO. Just make the function flexible enough to take different kinds of parameters. Have a closer look :

1 function add_to_cart($item_id , $qty)
2 {
3     if(!is_array($item_id))
4     {
5         $_SESSION['cart'][$item_id] = $qty;
6     }
7   
8     else
9     {
10         foreach($item_id as $i_id => $qty)
11         {
12             $_SESSION['cart'][$i_id] = $qty;
13         }
14     }
15 }
16   
17 add_to_cart( 'IPHONE3' , 2 );
18 add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );

So now the same function can accept different kinds of output. The above can be applied in lots of places to make your code more agile.

6. Omit the closing php tag if it is the last thing in a script

I wonder why this tip is omitted from so many blog posts on php tips.

1 <?php
2   
3 echo "Hello";
4   
5 //Now dont close this tag

This will save you lots of problem. Lets take an example :

A class file super_class.php

1 <?php
2 class super_class
3 {
4     function super_function()
5     {
6         //super code
7     }
8 }
9 ?>
10 //super extra character after the closing tag

Now index.php

1 require_once('super_class.php');
2   
3 //echo an image or pdf , or set the cookies or session data

And you will get Headers already send error. Why ? because the "super extra character" has been echoed , and all headers went along with that. Now you start debugging. You may have to waste many hours to find the super extra space.

Hence make it a habit to omit the closing tag :

1 <?php
2 class super_class
3 {
4     function super_function()
5     {
6         //super code
7     }
8 }
9   
10 //No closing tag

Thats better.

7. Collect all output at one place , and output at one shot to the browser

This is called output buffering. Lets say you have been echoing content from different functions like this :

1 function print_header()
2 {
3     echo "<div id='header'>Site Log and Login links</div>";
4 }
5   
6 function print_footer()
7 {
8     echo "<div id='footer'>Site was made by me</div>";
9 }
10   
11 print_header();
12 for($i = 0 ; $i < 100; $i++)
13 {
14     echo "I is : $i <br />';
15 }
16 print_footer();

Instead of doing like that , first collect all output in one place. You can either store it inside variables in the functions or use ob_start and ob_end_clean. So now it should look like

1 function print_header()
2 {
3     $o = "<div id='header'>Site Log and Login links</div>";
4     return $o;
5 }
6   
7 function print_footer()
8 {
9     $o = "<div id='footer'>Site was made by me</div>";
10     return $o;
11 }
12   
13 echo print_header();
14 for($i = 0 ; $i < 100; $i++)
15 {
16     echo "I is : $i <br />';
17 }
18 echo print_footer();

So why should you do output buffering :

  • You can change the output just before sending it to browser if you need to. Think about doing some str_replaces , or may be preg_replaces or may be adding some extra html at the end like profiler/debugger output
  • Its a bad idea to send output to browser and do php processing at the same time. Have you ever seen a website where there is a Fatal error in the sidebar or in a box in the middle of the screen. You know why that happens ? Because processing and output are being mixed.

8. Send correct mime types via header when outputting non-html content

Lets echo some xml.

1 $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
2 $xml = "<response>
3   <code>0</code>
4 </response>";
5   
6 //Send xml data
7 echo $xml;

Works fine. But it needs some improvement.

1 $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
2 $xml = "<response>
3   <code>0</code>
4 </response>";
5   
6 //Send xml data
7 header("content-type: text/xml");
8 echo $xml;

Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information.

Similarly for javascript , css , jpg image , png image :

Javascript

1 header("content-type: application/x-javascript");
2 echo "var a = 10";

CSS

1 header("content-type: text/css");
2 echo "#div id { background:#000; }";

9. Set the correct character encoding for a mysql connection

Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation.

1 $host = 'localhost';
2 $username = 'root';
3 $password = 'super_secret';
4   
5 //Attempt to connect to database
6 $c = mysqli_connect($host , $username, $password);
7           
8 //Check connection validity
9 if (!$c
10 {
11     die ("Could not connect to the database host: <br />". mysqli_connect_error());
12 }
13           
14 //Set the character set of the connection
15 if(!mysqli_set_charset ( $c , 'UTF8' ))
16 {
17     die('mysqli_set_charset() failed');
18 }

Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application.

Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.

10. Use htmlentities with the correct characterset option

Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc.

1 $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');

Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.

11. Do not gzip output in your application , make apache do that

Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php.

Use apache mod_gzip/mod_deflate to compress content via the .htaccess file.

12. Use json_encode when echoing javascript code from php

There are times when some javascript code is generated dynamically from php.

$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' ,];

Be smart. use json_encode :

$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"]

Isn't that neat ?

13. Check if directory is writable before writing any files

Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on.

Make sure that your application is as intelligent as possible and reports the most important information in the shortest time.

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

file_put_contents($file_path , $contents);

That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons :

  • Parent directory does not exist
  • Directory exists , but is not writable
  • File locked for writing ?

So its better to make everything clear before writing out to a file.

$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");
}

By doing this you get the accurate information that where is a file write failing and why

14. Change permission of files that your application creates

When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on.

// 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. Don't check submit button value to check form submission

if($_POST['submit'] == 'Save')
{
    //Save the things
}

The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this :

if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )
{
    //Save the things
}

Now you are free from the value the submit button

16. Use static variables in function where they always have same value

//Delay for some time
function delay()
{
    $sync_delay = get_option('sync_delay');

    echo "<br />Delaying for $sync_delay seconds...";
    sleep($sync_delay);
    echo "Done <br />";
}

Instead use static variables as :

//Delay for some time
function delay()
{
    static $sync_delay = null;

    if($sync_delay == null)
    {
	$sync_delay = get_option('sync_delay');
    }

    echo "<br />Delaying for $sync_delay seconds...";
    sleep($sync_delay);
    echo "Done <br />";
}

17. Don't use the $_SESSION variable directly

Some simple examples are :

$_SESSION['username'] = $username;
$username = $_SESSION['username'];

But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain.

Hence use application specific keys with wrapper functions :

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. Wrap utility helper functions into a class

So you have a lot of utility functions in a file like :

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 ...
}

And you use the function throughout your application freely. You may want to wrap them into a class as static functions :

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();

One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict.
Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.

19. Bunch of silly tips

  • Use echo instead of print
  • Use str_replace instead of preg_replace , unless you need it absolutely
  • Do not use short tags
  • Use single quotes instead of double quotes for simple strings
  • Always remember to do an exit after a header redirect
  • Never put a function call in a for loop control line.
  • isset is faster than strlen
  • Format your code correctly and consistently
  • Do not drop the brackets of loops or if-else blocks.
    Do not code like this : 

    if($a == true) $a_count++;

    Its absolutely a WASTE.

    Write

    if($a == true)
    {
        $a_count++;
    }

    Dont try to make your code shorter by eating up syntax. Rather make your logic shorter.

  • Use a proper text editor which has code highlighting. Code highlighting helps to create lesser errors.

20. Process arrays quickly with array_map

Lets say you want to trim all elements of an array. Newbies do it like this :

foreach($arr as $c => $v)
{
	$arr[$c] = trim($v);
}

But it can more cleaner with array_map :

$arr = array_map('trim' , $arr);

This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the
documentation on these to know more.

21. Validate data with php filters

Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets
try something different, called filters.

The php filter extension provides simple way to validate or check values as being a valid 'something'.

22. Force type checking

$amount = intval( $_GET['amount'] );
$rate = (int) $_GET['rate'];

Its a good habit.

23. Write Php errors to file using set_error_handler()

set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose

24. Handle large arrays carefully

Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded :

$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 ?

The above thing is common when importing a csv file or exporting table to a csv file

Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays.

Consider passing them by reference , or storing them in a class variable :

$a = get_large_array();
pass_to_function(&$a);

by doing this the same variable (and not its copy) will be available to the function. Check documentation

class A
{
    function first()
    {
        $this->a = get_large_array();
        $this->pass_to_function();
    }

    function pass_to_function()
    {
        //process $this->a
    }
}

unset them as soon as possible , so that memory is freed and rest of the script can relax.

Here is a simple demonstration of how assign by reference can save memory in some cases

<?php

ini_set('display_errors' , true);
error_reporting(E_ALL);

$a = array();

for($i = 0; $i < 100000 ; $i++)
{
	$a[$i] = 'A'.$i;
}

echo 'Memory usage in MB : '. memory_get_usage() / 1000000 . '<br />';

$b = $a;
$b[0] = 'B';

echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000 . '<br />';

$c = $a;
$c[0] = 'B';

echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000 . '<br />';

$d =& $a;
$d[0] = 'B';

echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000 . '<br />';

The output on a typical php 5.4 machine is :

Memory usage in MB : 18.08208
Memory usage in MB after 1st copy : 27.930944
Memory usage in MB after 2st copy : 37.779808
Memory usage in MB after 3st copy (reference) : 37.779864

So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.

25. Use a single database connection, throughout the script

Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this :

function add_to_cart()
{
    $db = new Database();
    $db->query("INSERT INTO cart .....");
}

function empty_cart()
{
    $db = new Database();
    $db->query("DELETE FROM cart .....");
}

Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory.

Use the singleton pattern for special cases like database connection.

26. Avoid direct SQL query , abstract it

$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";
$db->query($query); //call to mysqli_query()

The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like:

  • All values have to be escaped everytime manually
  • Manually verify the sql syntax everytime.
  • Wrong queries may go undetected for a long time (unless if else checking done everytime)
  • Difficult to maintain large queries like that

Solution: ActiveRecord

It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries.

A very simple example of an activerecord insert function can be like this :

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 to be inserted in database
$data = array('name' => $name , 'email' => $email  , 'address' => $address , 'phone' => $phone);
//perform the INSERT query
insert_record('users' , $data);

The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse).

This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.

27. Cache database generated content to static files

Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again.

Benefits :

  • Save php processing to generate the page , hence faster execution
  • Lesser database queries means lesser load on mysql database

28. Store sessions in database

File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue.

Storing session in database makes many other things easier like:

  • Restrict concurrent logins from same username. Same username cannot log in from 2 different places at same time
  • Check online status of users more accurately

29. Avoid using globals

  • Use defines/constants
  • Get value using a function
  • Use Class and access via $this

30. Use base url in head tag

Quick example :

<head>
    <base href="http://www.domain.com/store/">
</head>
<body>
    <img src="happy.jpg" />
</body>
</html>

The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories.

Lets take an example

www.domain.com/store/home.php
www.domain.com/store/products/ipad.php

In home.php the following can be written :

<a href="home.php">Home</a>
<a href="products/ipad.php">Ipad</a>

But in ipad.php the links have to be like this :

<a href="../home.php">Home</a>
<a href="ipad.php">Ipad</a>

This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag.

<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>

Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php

31. Manage error reporting

error_reporting is the function to use to set the necessary level of error reporting required.
On a development machine notices and strict messages may be disabled by doing.

ini_set('display_errors', 1);
error_reporting(~E_NOTICE & ~E_STRICT);

On production , the display should be disabled.

ini_set('display_errors', 0);
error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);

It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark.

After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set.

ini_set('log_errors' , '1');
ini_set('error_log' , '/path/to/errors.txt');

ini_set('display_errors' , 0);
error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);

Note :

1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there.

2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors.

3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver).

4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched.

5. Dont set error_reporting to 0. It will not log anything then.

Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file.

Set 'display_errors=On' in php.ini on development machine

On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set)
This is because any compile time fatal errors will now allow ini_set to execute , hence no error display
and a blank WHITE page.

Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work.

Set 'display_errors=Off' in php.ini on production machine

Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.

32. Be aware of platform architecture

The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results.

On a 64 bit machine you can see such output.

$ 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

But on a 32 bit machine all of them would give bool(false). Check here for more.

What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.

33. Dont rely on set_time_limit too much

If you are limiting the maximum run-time of a script , by doing this :

set_time_limit(30);

//Rest of the code

It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit.

So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.

34. Make a portable function for executing shell commands

system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it.

A better solution :

/**
	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');

The above function will execute the shell command using whichever function is available , keeping your code consistent.

35. Localize your application

Format dates and numbers properly. Show the time according to timezone of the user.
Check here to learn more.

36. Use a profiler like xdebug if you need to

Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise.

Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.

37. Use plenty of external libraries

An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily.

Few popular libraries are :

  • mPDF - Generate pdf documents, by converting html to pdf beautifully.
  • PHPExcel - Read and write Excel files
  • PhpMailer - Send html emails with attachments easily
  • pChart - Generate graphs in php

38. Have a look at phpbench for some micro-optimisation stats

If you really want to achieve optimisation at the level of microtime then check phpbench ... it has some benchmarks for various syntax variations that can create significant difference.

39. Use an MVC framework

Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.

  • Clean separation of php and html code. Good for team work, when designers and coders are working together.
  • Functions and functionalities are organised in classes making maintenance easy.
  • Inbuilt libraries for various needs like email, string processing, image processing, file uploads etc.
  • Is a must when writing big applications
  • Lots of tips, techniques, hacks are already implemented in the framework

40. Read the comments on the php documentation website

The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community.

They contain user feedback, expert advice and useful code snippets. So check them out.

41. Go to the IRC channel to ask

The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!

42. Read open source code

Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc.

The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more

1. Codeigniter
2. WordPress
3. Joomla CMS

43. Develop on Linux

If you are already developing on windows, then you might give Linux a try. My favorite is ubuntu. Although this is just an opinion but still I strongly feel that for development linux is a much better environment.

Php applications are mostly deployed on linux (LAMP) environments. Therefore, developing in a similar environment helps to produce a robust application faster.

Most of the development tools can be very easily installed from synaptic package manager in Ubuntu. Plus they need very little configuration to setup and run. And the best thing is, that they all are free.

Resources

http://www.phptherightway.com/

给我留言

Copyright © 浩然东方 保留所有权利.   Theme  Ality 07032740

用户登录