50 Practical tips for high quality PHP code (bottom) _php tips

Source: Internet
Author: User
Tags ereg explode php programming php redirect php template rar how to use sql gtar

Then the article "High-quality PHP Code 50 Practical Skills Necessary (above)" continue to study.

26. Avoid writing SQL directly, abstract
patiently wrote too many of the following statements:

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" > $query = "INSERT into the users (name, email, address, phone) VALUES (' $name ', ' $email ', ' $address ', ' $phone ')";
 $db->query ($query); Call to Mysqli_query () </span>

This is not a plan to build a strong one. It has some disadvantages:

    • >> manually escape values each time
    • >> Verify that the query is correct
    • >> query errors can take a long time to identify (unless you use a if-else check every time)
    • >> difficult to maintain complex queries

So use function encapsulation:

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" >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);</span>

Did you see it? This makes it easier to read and expand. The Record_data function handles the escape carefully. The biggest advantage is that the data is preprocessed into an array, and any grammatical errors are captured. The function should be defined in a database class, and you can call it like $db->insert_record. Check out this article to see how it's easier to work with your database. Similarly, you can write Update,select,delete methods. Give it a try.

27. Cache the database-generated content in a static file
if all of the content is retrieved from the database, they should be cached. Once they are generated, they are saved in a temporary file. The next time the page is requested, it can be taken directly from the cache without having to check the database again.
Benefits:
>> save time for PHP to process pages and perform faster
>> fewer database queries mean less MySQL connection overhead

28. Save session in Database
There are many limitations to the file-based session strategy. Using a file-based session cannot be extended to the cluster because the session is saved on a single server. However, the database can be accessed by multiple servers, which resolves the problem.
There are additional benefits to saving session data in the database:
>> handle username Repeat login problem. The same username cannot log in at the same time in two places.
>> can be more prepared to query online user status.

29. Avoid using global variables

    • >> Use Defines/constants
    • >> Get values using functions
    • >> use classes and access via $this

30. Use base label in head
never heard of him? Please look below:

 
 

Base tags are useful. Suppose your application is divided into subdirectories, and they all include the same navigation menu.

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

In the home page, you can write:

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

But in your ipad.php have to write:

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" ><a href= ". /home.php ">Home</a>
 <a href=" ipad.php ">Ipad</a></span>

Because the directory is not the same. There are so many different versions of the navigation menu to maintain, very bad AH. Therefore, use the base label.

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" > 
 

Now, the code will behave in the same directory file as the application.

31. Never set Error_reporting to 0
Turn off error reporting that is not a phase. It is important to e_fatal mistakes.

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" >ini_set (' display_errors ', 1);
 Error_reporting (~e_warning & ~e_notice & ~e_strict);</span>

32. Note Platform Architecture
integers are different in length in 32-bit and 64-bit architectures. Therefore, some functions, such as strtotime, behave differently.
In a 64-bit machine, you will see the following output.

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" >$ 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</span> 

But in 32-bit machines, they will be bool (false). See here for more information.

33. Do not rely too much on set_time_limit
if you want to limit the minimum time, you can use the following script:

<span style= "color: #333333; font-family: ' Helvetica, Arial, Sans-serif ';" >set_time_limit (a);
 Rest of the Code</span>

Do you have peace of mind? Note that any external execution, such as system calls, socket operations, database operations, and so on, is not under the control of Set_time_limits.
Therefore, even if the database spends a lot of time querying, the script will not stop executing. Depending on the situation.

34. Using an extension library
Some examples:

    • >>mpdf-can generate PDF documents via HTML
    • >>phpexcel-Read and write Excel
    • >>phpmailer-easy to handle sending messages containing nearby
    • >>pchart-use PHP to generate reports

Use open source libraries to accomplish complex tasks, such as generating PDFs, ms-excel files, reports, and more.

35. Using the MVC framework
It's time to use an MVC framework like CodeIgniter. The MVC framework does not force you to write object-oriented code. They only separate the PHP code from the HTML.

    • >> clearly differentiate between PHP and HTML code. The benefits of teamwork are that designers and programmers can work together.
    • >> Object-oriented design functions to make it easier for you to maintain
    • >> built-in functions do a lot of work, you don't need to write it over and over again
    • >> development of large applications is necessary
    • >> Many suggestions, tips and hack have been implemented by the framework

36. Often look at Phpbench
Phpbench provides benchmark results for basic PHP operations that show how some of the small variations of the grammar can cause significant differences.
Check the PHP site comments, have questions to IRC questions, often read open source code, using Linux development.

37. How to create a site's index page correctly
When creating each site, building the index page of the site is one of the first things to do. If you're a novice in PHP, the typical way to write the index page is to program only the content that is needed for the index page, and other links to create another page. However, if you want to learn a more efficient way to implement PHP programming, you can use the "Index.php?page=home" mode, which is used by many websites.

38. Fetching data using the request Global array
In fact, there's no reason to use $_get and $_post arrays to crawl values. $_request This global array allows you to obtain a Get or form request. Therefore, in most cases, the more efficient code for parsing data is generally as follows:

$action = Isset ($_request[' action ')? $_request[' action ': 0;

39. Using Var_dump to debug PHP code
If you're looking for PHP debugging techniques, I have to say that var_dump should be the target you're looking for. This command can meet all your needs in the display of PHP information. And most of the debugging code is about getting the values in PHP.

PHP handles code logic, Smarty process presentation layer
Smarty is one of the most famous PHP template engines in the industry, using PHP as a template for PHP templates. It separates the logical code from the external content, provides an easy to manage and use method to separate the PHP code from the original HTML code. Simply speaking, the goal is to make the PHP programmer with the front-end staff separation, so that the programmer changes the logic of the program will not affect the front-end staff of the page design, the front-end staff to modify the page does not affect the program logic, which in many people cooperation project is particularly important.

41. When you really need to use global values, create a config file
It's a bad idea to create global values at every turn, but sometimes the real thing really needs to be done. It's a good idea to use global values for database tables or database connection information, but don't use global values frequently in your PHP code. In addition, a better approach is to keep your global variables in a config.php file.

42. If not defined, no access!
If you create the page correctly, no one else has reason to visit index.php pages outside of index.php or home.php. Once index.php is accessed, you can open the page you want by getting the variable. Your index page should contain similar following code:

Define (' Yourpage ', 1);

The other pages should then contain:

if (!defined (' yourpage ')) die (' Access Denied ');

This is done to prevent direct access to your other PHP pages. In this way, anyone who tries to access other pages without index.php will get a "access denied" message.

43. Create a Database class
If you are working on database programming (a very common task in PHP), a good idea is to create a database class to handle any database management functionality. The sample code is as follows:

Public Function dbexec ($query)  
    
 {  
    
   $result = $this->db->exec ($query);  
    
   if (Pear::iserror ($result))  
    
     Errorredirect ($result->getmessage (), true);  
    
   else return 
    
     $result;  
    
 }

This function receives only one query statement and executes it. It also handles any errors that may occur. You can also include the audit code here, but I prefer to use a similar audit function:

Checks if arguments given are integer values not less than 0-has multiple arguments  
    
 function sanitizeinput () 
   {  
    
   $numargs = Func_num_args ();  
    
   $arg _list = Func_get_args ();  
    
   for ($i = 0; $i < $numargs; $i + +) {  
    
     if (!is_numeric ($arg _list[$i]) | | $arg _list[$i] < 0)  
    
       Errorredirect ("Un Expected variable Value ", true);  
    
   }  
    
 }

44. A php file processing input, a class.php file processing specific functions
One important way to keep your code from confusing is to get user input and redirect it to another function for processing. The principle is very simple, the php file gets any input we need, and then redirects it to a function in the class file. For example, suppose you have a URL that resembles "Index.php?page=profile&action=display". by profile.php to retrieve the URL and get the operation is "display". Then using a simple switch function, let's perform the actual display function:

Require_once projectroot. ' libs/messages.class.php ';  
    
$message = new Message ();  
    
Switch ($action) 
    
{case 
    
  ' display ': 
    
    $message->display (); 
    
    break;  
    
...



As shown above, I used a message class and started a switch check. $message is just an object that is used by the calling function in the class.

45. Understand your SQL statements and always review them (Sanitize)
as I mentioned before, 99% of the most important parts of any PHP site are probably databases. Therefore, you need to be very familiar with how to use SQL correctly. Learn to correlate tables and more advanced techniques. I'll show you a sample function using MySQL and review it using the 7th function of this article.

Private Function Getsentmessages ($id)  
    
 {  
    
$this->util->sanitizeinput ($id);  
    
  $PM _table = $GLOBALS [' config '] [' privatemsg '];  
    
 $users = $GLOBALS [' config '] [' users '];  
    
   $sql = "Select pm.*, Usr.username as Name_sender from $pm _table PM, $users USR  
    
     WHERE id_sender = ' $id ' and Sender_purg E = FALSE and usr.id = pm.id_receiver and Is_read = TRUE ORDER by  
    
     date_sent DESC ";  
    
 $result = $this->dbqueryall ($sql);  
    
  return $result;  
    
 }

First, we check the user input (passing the message ID through a get variable), and we execute our SQL command. Note the use of SQL here. You need to know how to use aliases and associated tables.

46. When you need only one object, use a single example mode
in a fairly common scenario in PHP, we only need to create an object once and then use it throughout our program. A good example is the Smarty variable, which can be used everywhere once it is initialized. A good implementation of this scenario is a single example pattern. The sample code is as follows:

function Smartyobject ()  
    
 {  
    
   if ($GLOBALS [' config '] [' smartyobj '] = = 0)  
    
   {  
    
     $smarty = new Smartygame ();  
    
     $GLOBALS [' config '] [' smartyobj '] = $smarty;  
    
   }  
    
   else 
    
     $smarty = $GLOBALS [' config '] [' smartyobj '];  
    
   return $smarty;  
    
 }

Note that we have a global smarty variable (which is initialized in config.php in this example), and if it has a value of 0, we will create a new Smarty object. Otherwise, it means that the object has been created and we just need to return it.

47. About PHP redirect
Method One:header ("Location:index.php");
method Two:echo "<script>window.location=\" $PHP _self\ ";</script>";
method Three:echo "<metahttp-equiv=\" refresh\ "content=\" 0; Url=index.php\ ">";

48. Get Visitor Browser

Functionbrowse_infor () {$browser = ""; $browserver = ""; $Browsers =array ("Lynx", "MOSAIC", "AOL", "Opera", "JAVA", "Macweb
"," Webexplorer "," OmniWeb ");
$Agent = $GLOBALS ["Http_user_agent"]; For ($i =0 $i <=7; $i + +) {if Strpos ($Agent, $Browsers [$i]) {$browser = $Browsers [$i]; $browserver = "";}} if (Ereg
Mozilla ", $Agent) &&!ereg (" MSIE ", $Agent)) {$temp =explode (" (", $Agent); $Part = $temp [0];
$temp =explode ("/", $Part); $browserver = $temp [1];
$temp =explode ("", $browserver); $browserver = $temp [0]; $browserver =preg_replace ("/([\d\.]
+)/"," \1 ", $browserver);
$browserver = "$browserver";
$browser = "Netscapenavigator";
if (Ereg ("Mozilla", $Agent) &&ereg ("Opera", $Agent)) {$temp =explode ("(", $Agent); $Part = $temp [1];
$temp =explode (")", $Part) $browserver = $temp [1];
$temp =explode ("", $browserver); $browserver = $temp [2]; $browserver =preg_replace ("/([\d\.]
+)/"," \1 ", $browserver);
$browserver = "$browserver";
$browser = "Opera"; } if (Ereg ("Mozilla", $Agent) &&ereg ("MSIE", $Agent)) {$temp =explode ("(", $Agent); $Part = $temp[1];
$temp =explode (";", $Part); $Part = $temp [1];
$temp =explode ("", $Part); $browserver = $temp [2]; $browserver =preg_replace ("/([\d\.]
+)/"," \1 ", $browserver);
$browserver = "$browserver";
$browser = "InternetExplorer";
} if ($browser!= "") {$browseinfo = "$browser $browserver";} else {$browseinfo = "Unknown";} return$browseinfo;
 ()//Call Method $browser=browseinfo (), return results directly

49. Get visitor Operating system

Functionosinfo () {$os = ""; $Agent = $GLOBALS ["Http_user_agent"]; if (eregi (' win ', $Agent) &&strpos ($Agent, ' 95 ') {$os = "Windows95";} elseif (Eregi (' Win9x ', $Agent) &&strpos ($Agent, ' 4.90 ')) {$os = "windowsme";} elseif ( ' Win ', $Agent) &&ereg (' n ', $Agent)) {$os = "Windows98";} elseif (Eregi (' win ', $Agent) &&eregi (' nt5\.0 ', $Agent)) {$os = "Windows2000";} elseif (Eregi (' win ', $Agent) &&eregi (' NT ', $Agent)) {$os = ' WindowsNT ';} elseif ( Eregi (' Win ', $Agent) &&eregi (' nt5\.1 ', $Agent)) {$os = "Windows XP";} elseif (Eregi (' win ', $Agent) &&ereg (' $Agent ')
{$os = "Windows32";} ElseIf (eregi (' Linux ', $Agent)) {$os = "Linux";} elseif (Eregi (' Unix ', $Agent)) {$os = "Unix"; ElseIf (Eregi (' Sun ', $Agent) &&eregi (' OS ', $Agent)) {$os = "SunOS";} elseif (Eregi (' IBM ', $Agent) &&eregi (' OS ', $Agent)) {$os = ' ibmos/
2 "; } elseif (Eregi (' Mac ', $Agent) &&eregi (' PC ', $Agent)) {$os = "Macintosh";} elseif (Eregi (' PowerPC ', $Agent)) {$os =
"PowerPC"; } elseif (Eregi (' AIX ', $Agent)) {$os ="AIX"; } elseif (Eregi (' HPUX ', $Agent)) {$os = "HPUX";} elseif (Eregi (' NetBSD ', $Agent)) {$os = ' NetBSD ';} elseif (' BSD ', $ Agent) {$os = "BSD";} elseif (Ereg (' OSF1 ', $Agent)) {$os = "OSF1";} elseif (Ereg (' IRIX ', $Agent)) {$os = ' IRIX ';} elseif (
Eregi (' FreeBSD ', $Agent)) {$os = "FreeBSD";} if ($os = = ") $os =" Unknown ";
Return$os;



 }//Call method $os=os_infor ();

50. File Format class

$mime _types=array (' gif ' => ' image/gif ', ' jpg ' => ' image/jpeg ', ' jpeg ' => ' image/jpeg ', ' jpe ' => ' ' image/jpeg '), ' BMP ' => ' image/bmp ', ' png ' => ' image/png ', ' tif ' => ' Image/tiff ', ' TIFF ' => ' Image/tiff ', ' pict ' => ' X-pict ', ' pic ' => ' image/x-pict ', ' pct ' => ' image/x-pict ', ' tif ' => ' Image/tiff ', ' TIFF ' => ' Image/tiff ', ' PSD ' => ' image/x-photoshop ', ' swf ' => ' application/x-shockwave-flash ', ' js ' => ' application/x-javascript ', ' pdf ' = > ' application/pdf ', ' ps ' => ' application/postscript ', ' eps ' => ' application/postscript ', ' ai ' => ' Application/postscript ', ' wmf ' => ' application/x-msmetafile ', ' css ' => ' text/css ', ' htm ' => ' text/html ', ' HTML ' => ' text/html ', ' txt ' => ' text/plain ', ' xml ' => ' text/xml ', ' WML ' => ' text/wml ', ' wbmp ' => ' Vnd.wap.wbmp ', ' mid ' => ' Audio/midi ', ' wav ' => ' audio/wav ', ' mp3 ' => ' audio/mpeg ', ' mp2 ' => ' audio/mpeg ', ' avi ' => ' Video/x-msvideo ', ' mpeg ' => ' video/mpeg ', ' mpg ' => ' video/mpeg ', ' qt ' => ' video/quicktIME ', ' mov ' => ' video/quicktime ', ' Lha ' => ' Application/x-lha ', ' lzh ' => ' Application/x-lha ', ' Z ' => ' Application/x-compress ', ' Gtar ' => ' Application/x-gtar ', ' gz ' => ' application/x-gzip ', ' gzip ' => ' application/ X-gzip ', ' tgz ' => ' application/x-gzip ', ' tar ' => ' application/x-tar ', ' bz2 ' => ' application/bzip2 ', ' Zip ' => ' Application/zip ', ' Arj ' => ' application/x-arj ', ' rar ' => ' application/x-rar-compressed ', ' hqx ' => ' /mac-binhex40 ', ' Sit ' => ' application/x-stuffit ', ' bin ' => ' application/x-macbinary ', ' uu ' => ' text/ X-uuencode ', ' Uue ' => ' text/x-uuencode ', ' latex ' => ' application/x-latex ', ' ltx ' => ' Application/x-latex ', ' Tcl ' => ' application/x-tcl ', ' PGP ' => ' application/pgp ', ' ASC ' => ' application/pgp ', ' exe ' => ' application/
X-msdownload ', ' Doc ' => ' Application/msword ', ' rtf ' => ' application/rtf ', ' xls ' => ' application/vnd.ms-excel ', ' ppt ' => ' application/vnd.ms-powerpoint ', ' mdb ' => ' application/x-msaccess ', ' wri ' => 'N/x-mswrite ',);
5. PHP generates Excel document.
Header ("Content-type:application/vnd.ms-excel");
Header ("Content-disposition:filename=test.xls");
echo "Test1\t";
echo "test2\t\n";
echo "Test1\t";
echo "test2\t\n";
echo "Test1\t";
echo "test2\t\n";
echo "Test1\t";
echo "test2\t\n";
echo "Test1\t";
echo "test2\t\n";
echo "Test1\t"; 
 echo "test2\t\n";?>//change the corresponding file header to output the. doc.xls file format

The above is the entire content of this article, we combine the previous in-depth study, there will be some gains.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.