search
HomeBackend DevelopmentPHP Tutorial10 very useful PHP tips for beginners, php tips for beginners_PHP tutorial

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

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

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

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

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

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

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

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

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

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>

5. Make functions 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 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) );

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

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

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

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

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

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;

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

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

请注意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; }"

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

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

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

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

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

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

从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
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool