10 Very useful PHP tips for beginners, beginner PHP tips _php Tutorial

Source: Internet
Author: User
Tags closing tag

10 Very useful PHP tips for beginners, beginner PHP Tips


This article introduces some tips and tricks for improving and optimizing PHP code for your reference, as follows

1. Do not use a relative path, define a root path

Such lines of code are common:

Require_once ('.. /.. /lib/some_class.php ');

There are many drawbacks to this approach:

1), it first search PHP including the path of the specified directory, and then view the current directory. Therefore, many directories are checked.
2), when a script is contained in a different directory of another script, its base directory becomes the directory containing the script.
3), another problem is that when a script runs from Cron, it may not use its parent directory as the working directory.
So using absolute paths becomes a good approach:

Define (' root ', '/var/www/project/'); require_once (Root. '.. /.. /lib/some_class.php ');//rest of the Code

This is an absolute path and will remain unchanged. However, we can further improve. Directory/var/www/project can change, then we have to change it every time?

No, using magic constants such as __file__ can make it portable. Please look carefully:

Suppose your script Is/var/www/project/index.php//then __file__ 'll always has that full path.define (' ROOT ', Pathinf O (__file__, pathinfo_dirname)); Require_once (ROOT. '.. /.. /lib/some_class.php ');//rest of the Code

So now, even if you move the project to a different directory, such as moving it to an online server, the code doesn't need to be changed to run.

2. Do not use require, including require_once or include_once

Your script might include a variety of files, such as class libraries, utility files, and auxiliary functions, just like these:

Require_once (' lib/database.php '); require_once (' lib/mail.php '); require_once (' helpers/utitlity_functions.php ');

It's pretty rough. The code needs to be more flexible. Writing helper functions makes it easier to include things. As an example:

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

Do you see the difference? It's obvious. There is no need for any more explanation.

You can also further improve:

function Load_class ($class _name) {  //path to the class file  $path = ROOT. '/lib/'. $class _name. '. php ');  if (file_exists ($path))  {    require_once ($path);}   }

Doing this can do a lot of things:

Search multiple directories for the same class file.
Easily change the directory that contains the class file without breaking code anywhere.
Use a similar function to load files that contain auxiliary functions, HTML content, and so on.

3. Maintaining the debugging environment in the application

During the development process, we echo the database query, dump the variables that created the problem, and then once the problem is resolved, we annotate them or delete them. But keeping everything in place can provide long-term help.

On the development computer, you can do this:

Define (' Environment ', ' development '); if (! $db->query ($query) {  if (environment = = ' development ')  {    echo "$query failed";  }  else  {    echo "Database error. Please contact administrator ";  }  }

And on the server, you can do this:

Define (' environment ', ' production '); if (! $db->query ($query) {  if (environment = = ' development ')  {    echo "$query failed";  }  else  {    echo "Database error. Please contact administrator ";  }  }

4. Propagating status messages through a session

Status messages are messages that are generated after the task is executed.

<?phpif ($wrong _username | | $wrong _password) {  $msg = ' Invalid username or password ';}? ><?php echo $msg;?>

Such code is common. The use of variables to display status information has some limitations. Because they cannot be sent by redirection (unless you propagate them to the next script as a get variable, it is very foolish). And there may be multiple messages in a large script, and so on.

The best way to do this is to use a session to propagate (even on the same page). If you want to do this, you must have a session_start on each page.

function Set_flash ($msg) {  $_session[' message '] = $msg;} function Get_flash () {  $msg = $_session[' message '];  unset ($_session[' message ');  return $msg;}

In your script:

<?phpif ($wrong _username | | $wrong _password) {  set_flash (' Invalid username or password ');}? >status is: <?php echo Get_flash ();?>

5. Make the function more flexible

function Add_to_cart ($item _id, $qty) {  $_session[' cart '] [$item _id] = $qty;} Add_to_cart (' IPHONE3 ', 2);

When adding a single entry, use the above function. So when you add multiple entries, do you have to create another function? NO. Just let the function become flexible so that it can accept different parameters. Please see:

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

Well, now the same function can accept different types of output. The above code can be used in many places to make your code more flexible.

6. Omit the end of the PHP tag if it is the last line in the script

I don't know why many blog posts omit this technique when talking about PHP tips.

<?phpecho "Hello";//now dont close this tag

This can help you omit a lot of problems. To give an example:

class file super_class.php

<?phpclass super_class{  function super_function ()  {    //super code  }}?>//super Extra character After the closing tag

Now look at index.php.

Require_once (' super_class.php ');//echo an image or PDF, or set the cookie or session data

You will get the header to send the error. Why is it? Because "super extra characters", all the headings go to deal with this. So you have to start debugging. You may need to waste a lot of time looking for super extra space.

So develop the habit of omitting the end tag:

<?phpclass super_class{  function super_function ()  {    //super code  }}//no closing tag

This is better.

7. Collect all outputs in one place and output them to the browser at once

This is called the output buffer. For example, you get something like this from a different function:

function Print_header () {  echo "Site Log and Login links";} function Print_footer () {  echo "Site was made by me";} Print_header (); for ($i = 0; $i < $i + +) {  
';} Print_footer ();

In fact, you should collect all the output in one place first. You can either store it inside a variable within a function, or use Ob_start and Ob_end_clean. So, it should look like this now.

function Print_header () {  $o = "Site Log and Login links";  return $o;} function Print_footer () {  $o = "Site is made by me";  return $o;} Echo Print_header (); for ($i = 0; $i < $i + +) {  
';} Echo Print_footer ();

So, why should you do output buffering:

You can change it before sending the output to the browser, if you need to. For example, do some str_replaces, or preg_replaces, or add some extra HTML at the end, such as the Profiler/debugger output.
Sending the output to the browser and doing PHP at the same time is not a good idea. Have you ever seen a site like this that has a fatal error in the sidebar or in the middle of the screen box? Do you know why this is happening? Because the process and output are mixed together.
8. When exporting non-HTML content, send the correct MIME type via the header

Take a look at some XML.

$xml = ' <?xml version= ' 1.0 "encoding=" Utf-8 "standalone=" yes "?>"; $xml = "
 
   
  
   0
 
  ";//send XML Dataecho $xml;

Works fine. But it needs some improvement.

$xml = ' <?xml version= ' 1.0 "encoding=" Utf-8 "standalone=" yes "?>"; $xml = "
 
   
  
   0
 
  ";//send XML Dataheader ("Content-type:text/xml"); Echo $xml;

Please note the header line. This line of code tells the browser that this content is XML content. Therefore, the browser is able to handle it correctly. Many JavaScript libraries also rely on header information.

Javascript,css,jpg pictures, PNG images are the same:

Javascript

Header ("Content-type:application/x-javascript"); echo "var a = 10"; Cssheader ("Content-type:text/css"); echo "#div ID {background: #000;}"

9. Set the correct character encoding for MySQL connection

There have been problems with unicode/utf-8 characters being stored correctly in MySQL tables, phpMyAdmin also shows that they are correct, but when you use them, your page does not display correctly. The secret lies in MySQL connection proofreading.

$host = ' localhost '; $username = ' root '; $password = ' Super_secret ';//attempt to connect to Database$c = Mysqli_connect ($hos T, $username, $password);//check connection Validityif (! $c) {  
". Mysqli_connect_error ());} Set the character set of the Connectionif (!mysqli_set_charset ($c, ' UTF8 ')) {die (' Mysqli_set_charset () failed ');}

Once you are connected to the database, you may want to set the connection character. This is absolutely necessary when you are using multiple languages in your application.

What else would happen? You will see a lot of boxes and????????。 in non-English text

10. Use the htmlentities with the correct character set option

Prior to PHP 5.4, the default character encoding used was iso-8859-1, which does not display characters such as Àâ.

$value = Htmlentities ($this->value, ent_quotes, ' UTF-8 ');

From PHP 5.4, the default encoding is UTF-8, which solves most of the problems, but you'd better know about it if your app uses multiple languages.

First introduce these 10 tips, the rest of the PHP tips we will be in the next article for everyone to share, thank you for your reading.

Articles you may be interested in:

    • PHP Delimiter usage Tips
    • PHP include_path Setup Tips sharing
    • PHP Array Operations summary PHP array usage tips
    • Tips for PHP recursive calls
    • PHP implementation of multiple images upload and watermark skills
    • A summary of some of the methods and techniques of error handling in PHP
    • PHP timestamp Strtotime () using methods and tricks
    • The application of JSON and JSON in PHP
    • PHP tips for JS and CSS Optimization tool minify use method
    • Dynamic access and usage tips for PHP namespaces (namespace)

http://www.bkjia.com/PHPjc/1120002.html www.bkjia.com true http://www.bkjia.com/PHPjc/1120002.html techarticle 10 useful PHP tips for beginners, beginner PHP Tips This article introduces some tips and tricks for improving and optimizing PHP code for your reference, as follows 1. Do not use ...

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