當前位置:才華齋>計算機>php語言>

初學者的30條PHP最佳實踐

php語言 閱讀(2.76W)

學會php可以在很多地方使用,比如做一個後臺登入的功能,要讓程式記住使用者,其實很簡單,看了下面的文章你就明白了。給初學者的30條PHP最佳實踐,需要的朋友可以參考下。

初學者的30條PHP最佳實踐

1,和PHP手冊成為好朋友

2,開啟Error Reporting

Error reporting 在 PHP 開發時是很有幫助的. 你可以在你程式碼中發現先前你沒有發現的錯誤,因為並不是所有的BUG都會讓程式執行不了的。當產品正式使用時,才有必要關掉錯誤報告,不然顧客看到一堆奇怪的字元不知道那是什麼意思。

3,使用IDE

IDE (整合開發環境,Integrated Development Environments)對於開發者來說是很有幫助的工具.

荒野在這裡推薦netbeans IDE 。

4. 試著使用一個PHP 框架

5.學習DRY方法

DRY 代表 Don't Repeat Yourself,它是一個有價值的程式設計概念,不管是什麼語言。DRY程式設計,顧名思義,是確保你不寫多餘的程式碼。

6.使用空格縮排程式碼來提高可讀性

7. “Tier” your Code

給你的應用程式分層,分成不同部位的不同組成部分的程式碼。這使得您可以輕鬆地在未來改變你的程式碼。 如常用的MVC模式。

8. 總是使用 <?php ?>

9.使用有意義的,一致的`命名約定

10.註釋、註釋、註釋

11.安裝MAMP/WAMP

12.給你的指令碼限制執行時間

通常PHP指令碼的執行時間被限制為30秒,超過這個時間PHP將丟擲一個致命錯誤。

13.使用OOP

14.知道雙引號和單引號的不同

15.不要在網站的根目錄放phpinfo()

16.永遠不要信任你的使用者

17.加密儲存密碼

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.使用視覺化資料庫設計工具

如 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.保護你的程式碼避免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 (object relational mapping)