10 useful PHP skills for beginners and php skills for beginners

Source: Internet
Author: User
Tags closing tag php error

10 useful PHP skills for beginners and php skills for beginners

This article introduces some tips and tips for improving and optimizing PHP code for your reference. The specific content is as follows:

1. Do not use relative paths. Define a root path

Such code lines are common:

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

This method has many disadvantages:

1) it first searches for the specified directory in the php including path and then displays the current directory. Therefore, many directories are checked.
2) When a script is included in different directories of another script, its basic 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.
Therefore, using absolute paths becomes a good method:

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 it. The directory/var/www/project can be changed. Do we need to change it every time?

No. Use a magic constant such as _ FILE _ to make it portable. Take a closer look:

//suppose your script is /var/www/project/index.php//Then __FILE__ will 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 a project to a different directory, such as moving it to an online server, the code can run without any changes.

2. Do not use require, including require_once or include_once

Your script may contain various files, such as class libraries, utility files, and auxiliary functions, like these:

require_once('lib/Database.php');require_once('lib/Mail.php');require_once('helpers/utitlity_functions.php');

This is rather rough. Code needs to be more flexible. Writing a helper function makes it easier to include things. For 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? Obviously. No more explanation is required.

You can 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 );   }}

This can accomplish many things:

Search multiple directories for the same class file.
Easily change the directory containing class files without damaging code anywhere.
Use similar functions to load files that contain helper functions and HTML content.

3. Maintain the debugging environment in the Application

During the development process, we echo database queries, dump the variables that create the problem, and once the problem is solved, we comment them or delete them. However, 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. Send status messages through sessions

Status messages are those generated after the task is executed.

<?phpif($wrong_username || $wrong_password){  $msg = 'Invalid username or password';}?>

Such code is very common. Using variables to display status information has certain limitations. Because they cannot be sent through redirection (unless you spread them as GET variables to the next script, but this is silly ). In addition, there may be multiple messages in large scripts.

The best way is to use sessions for propagation (even on the same page ). 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');}?>

5. Flexible Functions

function add_to_cart($item_id , $qty){  $_SESSION['cart'][$item_id] = $qty;}add_to_cart( 'IPHONE3' , 2 );

Use the above function when adding a single entry. So when multiple entries are added, do I have to create another function? NO. You only need to make the function flexible so that it can accept different parameters. 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) );

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 php tag. If it is the last line in the script

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

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

This helps you omit a large number of problems. For example:

Class file super_class.php

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

Now let's look at index. php.

require_once('super_class.php');//echo an image or pdf , or set the cookies or session data

You will get the sending error Header. Why? Because "Super redundant characters", all titles are processed. So you have to start debugging. You may need to waste a lot of time looking for extra space.

Therefore, we need to 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 then output them to the browser at a time.

This is the so-called output buffer. For example, you get something like this from different functions:

function print_header(){  echo "<div id='header'>Site Log and Login links</div>";}function print_footer(){  echo "<div id='footer'>Site was made by me</div>";}print_header();for($i = 0 ; $i < 100; $i++){  echo "I is : $i <br />';}print_footer();

In fact, you should first collect all the output in one place. You can either store the variable in the 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 was made by me</div>";  return $o;}echo print_header();for($i = 0 ; $i < 100; $i++){  echo "I is : $i <br />';}echo print_footer();

So why should you buffer the output:

You can change the output before sending it to the browser, if needed. For example, do some str_replaces, or preg_replaces, or add some additional html at the end, such as profiler/debugger output.
It is not a good idea to send the output to the browser and perform php processing at the same time. Have you ever seen a website with a Fatal error in the sidebar or in the box in the middle of the screen? Do you know why? Because the processing process and output are mixed together.
8. When non-HTML content is output, the correct mime type is sent through the header.

See some XML.

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

Working properly. But it requires some improvements.

$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';$xml = "<response> <code>0</code></response>";//Send xml dataheader("content-type: text/xml");echo $xml;

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

JavaScript, css, JPG, and 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 correct character encoding for MySQL connections

I have encountered the problem that unicode/UTF-8 characters are correctly stored in mysql tables. phpmyadmin also shows that they are correct, but when you use them, your webpage cannot be correctly displayed. The secret lies in MySQL connection verification.

$host = 'localhost';$username = 'root';$password = 'super_secret';//Attempt to connect to database$c = mysqli_connect($host , $username, $password);//Check connection validityif (!$c) {  die ("Could not connect to the database host: <br />". mysqli_connect_error());}//Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )){  die('mysqli_set_charset() failed');}

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

Otherwise, what will happen? You will see a lot of boxes and ????????.

10. Use htmlentities with the correct character set options

Before PHP 5.4, the default character encoding used is a ISO-8859-1, which cannot display characters such as â.

$value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');

From PHP 5.4, the default code is UTF-8, which solves most of the problem, but you 'd better know it if your application uses multiple languages.

We will introduce these 10 tips first. The remaining PHP skills will be shared with you in the following articles. Thank you for reading them.

Articles you may be interested in:
  • PHP delimiter usage tips
  • PHP shortde_path setting tips
  • PHP Array Operations summary php array usage tips
  • Tips for PHP recursive call
  • Php Watermarking Techniques for uploading multiple images
  • Php Error Handling Methods and Techniques
  • PHP timestamp strtotime () usage and tips
  • Application Skills of JSON and JSON in PHP
  • PHP tips: How to Use JS and CSS optimization tool Minify
  • PHP namespace dynamic access and usage skills

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.