10 Very useful PHP tips for beginners _php tips

Source: Internet
Author: User
Tags closing tag parent directory

This article introduces some tips and techniques for improving and optimizing PHP code, for your reference, the details are as follows

1. Do not use a relative path, to 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 searches for PHP including the specified directory in the path, and then view the current directory. As a result, 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 it's a good way to use an absolute path:

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 every time?

No, use magic constants like __file__ to make it portable. Please look carefully:

Suppose your script is/var/www/project/index.php
//then __file__ 'll always have that full path.

Define (' ROOT ', PathInfo (__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 scripts may include various 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. Code needs to be more flexible. Writing auxiliary 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 explanations.

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 so can accomplish many things:

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

3. Maintaining the debugging environment in the application

In the development process, we echo the database query, dump the variables that create the problem, and then, once the problem is resolved, we annotate them or delete them. But keeping everything in place can provide long-lasting 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. Propagate status messages through sessions

Status messages are those that are generated when a task is executed.

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

This kind of code is very common. The use of variables to display state information has certain limitations. Because they cannot be sent through redirection (unless you propagate them to the next script as a Get variable, this is very stupid). And there may be more than one message in a large script.

The best approach is to use a session to propagate (even on the same page). If you want to do this, you have to 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:

<?php
if ($wrong _username | | $wrong _password)
{
  set_flash (' Invalid username or password ');
>
 
 

5. Let the function become flexible

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

Add_to_cart (' IPHONE3 ', 2);

When you add a single entry, use the above function. So when you add multiple entries, 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));

OK, now the same function can accept different types of output. The above code can be applied to 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 a lot of blog posts are going to omit this technique when talking about PHP tips.

<?php

echo "Hello";

Now dont close this tag

This can help you omit a lot of questions. Give an example:

class file super_class.php

<?php
class 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, then? Because of "super extra character", all headings are going to take care of this. So you have to start debugging. You may need to waste a lot of time looking for extra space.

So get into the habit of omitting the end tag:

<?php
class Super_class
{
  function super_function ()
  {
    //super code
  }
}

//no Closing tag

It's better.

7. Collect all output in one place and output it 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 "<div id= ' header ' >site Log and Login links</div>";
}

function Print_footer ()
{
  echo "<div id= ' footer ' >site is made by me</div>";
}

Print_header ();
for ($i = 0; $i < $i + +)
{
  echo ' I is: $i <br/> ';
}
Print_footer ();

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

function Print_header ()
{
  $o = "<div id= ' header ' >site Log and Login links</div>";
  return $o;
}

function Print_footer ()
{
  $o = "<div id= ' footer ' >site is made by me</div>";
  return $o;
}

Echo Print_header ();
for ($i = 0; $i < $i + +)
{
  echo ' I is: $i <br/> ';
}
Echo Print_footer ();

So why do you have to do output buffering:

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

Take a look at some XML.

$xml = ' <?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?> ';
$xml = "<response>
 <code>0</code>
</response>";

Send XML Data
echo $xml;

Work properly. But it needs some improvement.

$xml = ' <?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?> ';
$xml = "<response>
 <code>0</code>
</response>";

Send XML Data
header ("Content-type:text/xml");
Echo $xml;

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

Javascript,css,jpg picture, the PNG image is the same:

Javascript

Header ("Content-type:application/x-javascript");
echo "var a = ten";
CSS

Header ("Content-type:text/css");
echo "#div ID {background: #000;}"

9. Set the correct character encoding for the MySQL connection

Having encountered unicode/utf-8 characters correctly stored in the MySQL table, phpMyAdmin also shows that they are correct, but when you use it, your Web page does not display correctly. The secret lies in the MySQL connection proofing.

$host = ' localhost ';
$username = ' root ';
$password = ' Super_secret ';

Attempt to connect to database
$c = Mysqli_connect ($host, $username, $password);

Check Connection Validity
if (! $c) 
{
  die ("Could not connect to" database host: <br/>. Mysqli_con Nect_error ());
}

Set the character set of the connection
if (!mysqli_set_charset ($c, ' UTF8 '))
{
  die (' Mysqli_set_charse T () failed ');


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

Otherwise, what would happen? You will see a lot of boxes and????????。 in non-English text

10. Using Htmlentities with the correct character set option

Before PHP 5.4, the default character encoding used was iso-8859-1, which could 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 problem, but you'd better know it if your application uses multiple languages.

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

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.