給初學(xué)者的30條PHP最佳實(shí)踐(荒野無(wú)燈)
更新時(shí)間:2011年08月02日 19:22:23 作者:
給初學(xué)者的30條PHP最佳實(shí)踐,需要的朋友可以參考下。
1,和PHP手冊(cè)成為好朋友
2,打開Error Reporting
Error reporting 在 PHP 開發(fā)時(shí)是很有幫助的. 你可以在你代碼中發(fā)現(xiàn)先前你沒有發(fā)現(xiàn)的錯(cuò)誤,因?yàn)椴⒉皇撬械腂UG都會(huì)讓程序運(yùn)行不了的。當(dāng)產(chǎn)品正式使用時(shí),才有必要關(guān)掉錯(cuò)誤報(bào)告,不然顧客看到一堆奇怪的字符不知道那是什么意思。
3,使用IDE
IDE (集成開發(fā)環(huán)境,Integrated Development Environments)對(duì)于開發(fā)者來(lái)說(shuō)是很有幫助的工具.
荒野在這里推薦netbeans IDE 。
4. 試著使用一個(gè)PHP 框架
5.學(xué)習(xí)DRY方法
DRY 代表 Don't Repeat Yourself,它是一個(gè)有價(jià)值的編程概念,不管是什么語(yǔ)言。DRY編程,顧名思義,是確保你不寫多余的代碼。
6.使用空格縮進(jìn)代碼來(lái)提高可讀性
7. “Tier” your Code
給你的應(yīng)用程序分層,分成不同部位的不同組成部分的代碼。這使得您可以輕松地在未來(lái)改變你的代碼。 如常用的MVC模式。
8. 總是使用 <?php ?>
9.使用有意義的,一致的命名約定
10.注釋、注釋、注釋
11.安裝MAMP/WAMP
12.給你的腳本限制運(yùn)行時(shí)間
通常PHP腳本的運(yùn)行時(shí)間被限制為30秒,超過(guò)這個(gè)時(shí)間PHP將拋出一個(gè)致命錯(cuò)誤。
13.使用OOP
14.知道雙引號(hào)和單引號(hào)的不同
15.不要在網(wǎng)站的根目錄放phpinfo()
16.永遠(yuǎn)不要信任你的用戶
17.加密存儲(chǔ)密碼
Rebuttal:
Keep in mind, however, that MD5 hashes have long since been compromised. They're absolutely more secure than not, but, with the use of an enormous “rainbow table,” hackers can cross reference your hash. To add even more security, consider adding a salt as well. A salt is basically an additional set of characters that you append to the user's string.
18.使用可視化數(shù)據(jù)庫(kù)設(shè)計(jì)工具
如 DBDesigner 和 MySQL Workbench
19.使用輸出緩沖
Rebuttal: Though not required, it's generally considered to be a good practice to go ahead and append the “ob_end_flush();” function as well to the bottom of the document. P.S. Want to compress the HTML as well? Simply replace “ob_start();” with “ob_start(‘ob_gzhandler')”;
Refer to this Dev-tips article for more information.
<!DOCTYPE html>
<?php ob_start('ob_gzhandler'); ?>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
20.保護(hù)你的代碼避免SQL注射
$username = mysql_real_escape_string( $GET['username'] );
$id = $_GET['id'];
$statement = $connection->prepare( "SELECT * FROM tbl_members WHERE id = ?" );
$statement->bind_param( "i", $id );
$statement->execute();
By using prepared statements, we never embed the user's inputted data directly into our query. Instead, we use the “bind_param” method to bind the values (and escaping) to the query. Much safer, and, notably, faster when executing multiple CRUD statements at once.
21.嘗試ORM?。╫bject relational mapping)
ORM libraries for PHP like Propel, and ORM is built into PHP frameworks like CakePHP.
22.緩存數(shù)據(jù)庫(kù)驅(qū)動(dòng)頁(yè)面
如:
// TOP of your script
$cachefile = 'cache/'.basename($_SERVER['SCRIPT_URI']);
$cachetime = 120 * 60; // 2 hours
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
include($cachefile);
echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
exit;
}
ob_start(); // start the output buffer
// Your normal PHP script and HTML content here
// BOTTOM of your script
$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp); // close the file
ob_end_flush(); // Send the output to the browser
23.使用緩存系統(tǒng)
24.驗(yàn)證Cookie數(shù)據(jù)
Cookie data, like any data passed on the Web, can be harmful. You can validate cookie data with either the htmlspecialchars() or mysql_real_escape_string().
25.使用靜態(tài)文件緩存系統(tǒng)
如Smarty的是一個(gè)內(nèi)置緩存的強(qiáng)大的模板系統(tǒng)。
26.分析你的代碼
Profiling your code with a tool like xdebug can help you to quickly spot bottlenecks and other potential problems in your PHP code. Some IDEs like Netbeans have PHP profiling capabilities as well.
27.編碼標(biāo)準(zhǔn)
如 Pear標(biāo)準(zhǔn)。
28. Keep Functions Outside of Loops
You take a hit of performance when you include functions inside of loops. The larger the loop that you have, the longer the execution time will take. Take the extra time and line of code and place the function outside of the loop.
Editor's Note: Think of it this way. Try to remove as many operations from the loop as possible. Do you really need to create that variable for every iteration of the loop? Do you really need to create the function each time? Of course not.
29.不要復(fù)制不額外的變量(事實(shí)上這一條值得懷疑,見下面的說(shuō)明)
如:
$description = strip_tags($_POST['description']);
echo $description;
可以寫成如下:
echo strip_tags($_POST['description']);
Rebuttal: In reference to the comment about “doubling the memory,” this actually is a common misconception. PHP implements “copy-on-write” memory management. This basically means that you can assign a value to as many variables as you like without having to worry about the data actually being copied. While it's arguable that the “Good” example exemplified above might make for cleaner code, I highly doubt that it's any quicker.
也就是說(shuō)PHP實(shí)現(xiàn)“copy-on-write” 的內(nèi)存管理方式,上面第一種代碼并不會(huì)存在占用雙倍內(nèi)存的情況。因此Rebuttal嚴(yán)重懷疑第二種方式的代碼是否真的比前面的快。
30.更新到最新版本的PHP
31.減少數(shù)據(jù)庫(kù)查詢次數(shù)
32.勇敢地提問
像StackOverflow等都是好去處。
2,打開Error Reporting
Error reporting 在 PHP 開發(fā)時(shí)是很有幫助的. 你可以在你代碼中發(fā)現(xiàn)先前你沒有發(fā)現(xiàn)的錯(cuò)誤,因?yàn)椴⒉皇撬械腂UG都會(huì)讓程序運(yùn)行不了的。當(dāng)產(chǎn)品正式使用時(shí),才有必要關(guān)掉錯(cuò)誤報(bào)告,不然顧客看到一堆奇怪的字符不知道那是什么意思。
3,使用IDE
IDE (集成開發(fā)環(huán)境,Integrated Development Environments)對(duì)于開發(fā)者來(lái)說(shuō)是很有幫助的工具.
荒野在這里推薦netbeans IDE 。
4. 試著使用一個(gè)PHP 框架
5.學(xué)習(xí)DRY方法
DRY 代表 Don't Repeat Yourself,它是一個(gè)有價(jià)值的編程概念,不管是什么語(yǔ)言。DRY編程,顧名思義,是確保你不寫多余的代碼。
6.使用空格縮進(jìn)代碼來(lái)提高可讀性
7. “Tier” your Code
給你的應(yīng)用程序分層,分成不同部位的不同組成部分的代碼。這使得您可以輕松地在未來(lái)改變你的代碼。 如常用的MVC模式。
8. 總是使用 <?php ?>
9.使用有意義的,一致的命名約定
10.注釋、注釋、注釋
11.安裝MAMP/WAMP
12.給你的腳本限制運(yùn)行時(shí)間
通常PHP腳本的運(yùn)行時(shí)間被限制為30秒,超過(guò)這個(gè)時(shí)間PHP將拋出一個(gè)致命錯(cuò)誤。
13.使用OOP
14.知道雙引號(hào)和單引號(hào)的不同
15.不要在網(wǎng)站的根目錄放phpinfo()
16.永遠(yuǎn)不要信任你的用戶
17.加密存儲(chǔ)密碼
Rebuttal:
Keep in mind, however, that MD5 hashes have long since been compromised. They're absolutely more secure than not, but, with the use of an enormous “rainbow table,” hackers can cross reference your hash. To add even more security, consider adding a salt as well. A salt is basically an additional set of characters that you append to the user's string.
18.使用可視化數(shù)據(jù)庫(kù)設(shè)計(jì)工具
如 DBDesigner 和 MySQL Workbench
19.使用輸出緩沖
Rebuttal: Though not required, it's generally considered to be a good practice to go ahead and append the “ob_end_flush();” function as well to the bottom of the document. P.S. Want to compress the HTML as well? Simply replace “ob_start();” with “ob_start(‘ob_gzhandler')”;
Refer to this Dev-tips article for more information.
復(fù)制代碼 代碼如下:
<!DOCTYPE html>
<?php ob_start('ob_gzhandler'); ?>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
20.保護(hù)你的代碼避免SQL注射
復(fù)制代碼 代碼如下:
$username = mysql_real_escape_string( $GET['username'] );
$id = $_GET['id'];
$statement = $connection->prepare( "SELECT * FROM tbl_members WHERE id = ?" );
$statement->bind_param( "i", $id );
$statement->execute();
By using prepared statements, we never embed the user's inputted data directly into our query. Instead, we use the “bind_param” method to bind the values (and escaping) to the query. Much safer, and, notably, faster when executing multiple CRUD statements at once.
21.嘗試ORM?。╫bject relational mapping)
ORM libraries for PHP like Propel, and ORM is built into PHP frameworks like CakePHP.
22.緩存數(shù)據(jù)庫(kù)驅(qū)動(dòng)頁(yè)面
如:
復(fù)制代碼 代碼如下:
// TOP of your script
$cachefile = 'cache/'.basename($_SERVER['SCRIPT_URI']);
$cachetime = 120 * 60; // 2 hours
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
include($cachefile);
echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
exit;
}
ob_start(); // start the output buffer
// Your normal PHP script and HTML content here
// BOTTOM of your script
$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp); // close the file
ob_end_flush(); // Send the output to the browser
23.使用緩存系統(tǒng)
24.驗(yàn)證Cookie數(shù)據(jù)
Cookie data, like any data passed on the Web, can be harmful. You can validate cookie data with either the htmlspecialchars() or mysql_real_escape_string().
25.使用靜態(tài)文件緩存系統(tǒng)
如Smarty的是一個(gè)內(nèi)置緩存的強(qiáng)大的模板系統(tǒng)。
26.分析你的代碼
Profiling your code with a tool like xdebug can help you to quickly spot bottlenecks and other potential problems in your PHP code. Some IDEs like Netbeans have PHP profiling capabilities as well.
27.編碼標(biāo)準(zhǔn)
如 Pear標(biāo)準(zhǔn)。
28. Keep Functions Outside of Loops
You take a hit of performance when you include functions inside of loops. The larger the loop that you have, the longer the execution time will take. Take the extra time and line of code and place the function outside of the loop.
Editor's Note: Think of it this way. Try to remove as many operations from the loop as possible. Do you really need to create that variable for every iteration of the loop? Do you really need to create the function each time? Of course not.
29.不要復(fù)制不額外的變量(事實(shí)上這一條值得懷疑,見下面的說(shuō)明)
如:
復(fù)制代碼 代碼如下:
$description = strip_tags($_POST['description']);
echo $description;
可以寫成如下:
echo strip_tags($_POST['description']);
Rebuttal: In reference to the comment about “doubling the memory,” this actually is a common misconception. PHP implements “copy-on-write” memory management. This basically means that you can assign a value to as many variables as you like without having to worry about the data actually being copied. While it's arguable that the “Good” example exemplified above might make for cleaner code, I highly doubt that it's any quicker.
也就是說(shuō)PHP實(shí)現(xiàn)“copy-on-write” 的內(nèi)存管理方式,上面第一種代碼并不會(huì)存在占用雙倍內(nèi)存的情況。因此Rebuttal嚴(yán)重懷疑第二種方式的代碼是否真的比前面的快。
30.更新到最新版本的PHP
31.減少數(shù)據(jù)庫(kù)查詢次數(shù)
32.勇敢地提問
像StackOverflow等都是好去處。
相關(guān)文章
php獲取目錄中所有文件名及判斷文件與目錄的簡(jiǎn)單方法
下面小編就為大家?guī)?lái)一篇php獲取目錄中所有文件名及判斷文件與目錄的簡(jiǎn)單方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-03-03微信公眾平臺(tái)開發(fā)教程②微信端分享功能圖文詳解
這篇文章主要介紹了微信公眾平臺(tái)開發(fā)微信端分享功能,結(jié)合圖文形式詳細(xì)分析了微信分享功能的原理、操作步驟及相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-04-04php轉(zhuǎn)換上傳word文件為PDF的方法【基于COM組件】
這篇文章主要介紹了php轉(zhuǎn)換上傳word文件為PDF的方法,結(jié)合實(shí)例形式分析了php基于COM組件針對(duì)word文件的格式轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下2019-06-06php的$_FILES的臨時(shí)儲(chǔ)存文件與回收機(jī)制實(shí)測(cè)過(guò)程
上傳文件是怎么個(gè)原理,大概的想了下,應(yīng)該是一種回收機(jī)制:點(diǎn)擊了臨時(shí)文件空間,那么,php自身應(yīng)該自己維護(hù)這塊空間的回收,具體的測(cè)試過(guò)程如下,感興趣的朋友可以參考下哈2013-07-07PHP中一個(gè)有趣的preg_replace函數(shù)詳解
這篇文章主要給大家介紹了關(guān)于PHP中一個(gè)有趣的preg_replace函數(shù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用php具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08