Table of Contents
10 very useful PHP tips for beginners, php tips for beginners
您可能感兴趣的文章:
Home Backend Development PHP Tutorial 10 very useful PHP tips for beginners, php tips for beginners_PHP tutorial

10 very useful PHP tips for beginners, php tips for beginners_PHP tutorial

Jul 12, 2016 am 08:54 AM
php Skill

10 very useful PHP tips for beginners, php tips for beginners

This article introduces some tips and tricks on improving and optimizing PHP code for your reference, specific content As follows

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

Lines like this are common:

require_once('../../lib/some_class.php');
Copy after login

This approach has many disadvantages:

1), It first searches the specified directory in the php include path, and then checks the current directory. Therefore, many directories are checked.
2) When a script is included in a different directory of another script, its base directory becomes the directory containing the script.
3) Another problem is that when a script is run from cron, it may not use its parent directory as the working directory.
So using absolute paths becomes a good method:

define('ROOT' , '/var/www/project/');
require_once(ROOT . '../../lib/some_class.php');

//rest of the code

Copy after login

This is an absolute path and will remain unchanged. However, we can improve further. The directory /var/www/project can be changed, so do we have to change it every time?

No, using magic constants like __FILE__ can make it portable. Please look carefully:

//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

Copy after login

So now, even if you move the project to a different directory, such as moving it to an online server, the code will run without changes.

2. Do not use require, including require_once or include_once

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

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

require_once('helpers/utitlity_functions.php');

Copy after login

This is pretty rough. The code needs to be more flexible. Writing helper functions 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');

Copy after login

See the difference? It's obvious. Doesn't require any more explanation.

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

Copy after login

You can accomplish a lot by doing this:

Search multiple directories for the same class file.
Easily change directories containing class files without breaking code anywhere.
Use similar functions for loading files containing helper functions, HTML content, etc.

3. Maintain debugging environment in the application

During development, we echo database queries, dump the variables that created the problem, and then once the problem is resolved, we comment them out or delete them. But leaving everything in place can provide long-lasting help.

On your 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";
  }  
}

Copy after login

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";
  }  
}

Copy after login

4. Propagate status messages through sessions

Status messages are those generated after executing a task.

<&#63;php
if($wrong_username || $wrong_password)
{
  $msg = 'Invalid username or password';
}
&#63;>
<html>
<body>

<&#63;php echo $msg; &#63;>

<form>
...
</form>
</body>
</html>

Copy after login

Code like this is very common. Using variables to display status information has certain limitations. Because they can't be sent via redirects (unless you propagate them as GET variables to the next script, but that's pretty stupid). And in large scripts there may be multiple messages etc.

The best way is to use sessions to propagate (even on the same page). To do this there must be a session_start on each page.

function set_flash($msg)
{
  $_SESSION['message'] = $msg;
}

function get_flash()
{
  $msg = $_SESSION['message'];
  unset($_SESSION['message']);
  return $msg;
}

Copy after login

In your script:

<&#63;php
if($wrong_username || $wrong_password)
{
  set_flash('Invalid username or password');
}
&#63;>
<html>
<body>

Status is : <&#63;php echo get_flash(); &#63;>
<form>
...
</form>
</body>
</html>

Copy after login

5. Make functions flexible

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

add_to_cart( 'IPHONE3' , 2 );

Copy after login

When adding a single entry, use the above function. So when adding multiple entries, do I have to create another function? NO. Just make the function 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) );

Copy after login

Okay, 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 closing php tag if it is the last line in the script

I don’t know why many blog posts omit this tip when talking about php tips.

<&#63;php

echo "Hello";

//Now dont close this tag

Copy after login

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

Class file super_class.php

<&#63;php
class super_class
{
  function super_function()
  {
    //super code
  }
}
&#63;>
//super extra character after the closing tag
Copy after login

Now look at index.php

require_once('super_class.php');

//echo an image or pdf , or set the cookies or session data

Copy after login

You will get the wrong header sent. Why? Because of "super redundant characters", all titles have 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 make a habit of omitting the closing tag:

<&#63;php
class super_class
{
  function super_function()
  {
    //super code
  }
}

//No closing tag

Copy after login

This is better.

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

This is called output buffering. Let's say 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 was made by me</div>";
}

print_header();
for($i = 0 ; $i < 100; $i++)
{
  echo "I is : $i <br />';
}
print_footer();

Copy after login

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

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

Copy after login

So why should you do output buffering:

你可以在将输出发送给浏览器之前更改它,如果你需要的话。例如做一些str_replaces,或者preg_replaces,又或者是在末尾添加一些额外的html,例如profiler/debugger输出。
发送输出给浏览器,并在同一时间做php处理并不是好主意。你见过这样的网站,它有一个Fatal error在侧边栏或在屏幕中间的方框中吗?你知道为什么会出现这种情况吗?因为处理过程和输出被混合在了一起。
8.当输出非HTML内容时,通过header发送正确的mime类型

请看一些XML。

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

//Send xml data
echo $xml;

Copy after login

工作正常。但它需要一些改进。

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

//Send xml data
header("content-type: text/xml");
echo $xml;

Copy after login

请注意header行。这行代码告诉浏览器这个内容是XML内容。因此,浏览器能够正确地处理它。许多JavaScript库也都依赖于header信息。

JavaScript,css,jpg图片,png图像也是一样:

JavaScript

header("content-type: application/x-javascript");
echo "var a = 10";
CSS

header("content-type: text/css");
echo "#div id { background:#000; }"

Copy after login

9.为MySQL连接设置正确的字符编码

曾碰到过unicode/utf-8字符被正确地存储在mysql表的问题,phpmyadmin也显示它们是正确的,但是当你使用的时候,你的网页上却并不能正确地显示。里面的奥妙在于MySQL连接校对。

$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 the database host: <br />". mysqli_connect_error());
}

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

Copy after login

一旦你连接到数据库,不妨设置连接字符集。当你在你的应用程序中使用多种语言时,这绝对有必要。

否则会发生什么呢?你会在非英文文本中看到很多的方框和????????。

10.使用带有正确字符集选项的htmlentities

PHP 5.4之前,使用的默认字符编码是ISO-8859-1,这不能显示例如À â 这样的字符。

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

从PHP 5.4起,默认编码成了UTF-8,这解决了大部分的问题,但你最好还是知道这件事,如果你的应用程序使用多种语言的话。

先介绍这10个技巧,剩下的PHP技巧我们将在接下来的文章中为大家分享,感谢您的阅读。

您可能感兴趣的文章:

  • PHP 定界符 使用技巧
  • PHP include_path设置技巧分享
  • PHP数组操作汇总 php数组的使用技巧
  • PHP递归调用的小技巧讲解
  • php实现多张图片上传加水印技巧
  • php一些错误处理的方法与技巧总结
  • PHP时间戳 strtotime()使用方法和技巧
  • 关于JSON以及JSON在PHP中的应用技巧
  • PHP小技巧之JS和CSS优化工具Minify的使用方法
  • PHP命名空间(namespace)的动态访问及使用技巧

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1120002.htmlTechArticle10个对初学者非常有用的PHP技巧,初学者php技巧 本文介绍一些关于改善和优化PHP代码的提示和技巧,供大家参考,具体内容如下 1.不要使用...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles