search
HomeBackend DevelopmentPHP TutorialA powerful tool for PHP debugging: PHPDBG_php skills

PHPDBG is a PHP SAPI module that can control the PHP operating environment without modifying the code or affecting performance.

PHPDBG aims to become a lightweight, powerful and easy-to-use PHP debugging platform. Can be used in PHP5.4 and above. In php5.6 and above versions will be integrated internally.

Main functions:

– Single-step debugging

– Flexible breakpoint method (class method, function, file: line, memory address, opcode)

– You can directly call php’s eval

– You can view the currently executing code

– User Space API (userland/user space)

– Easy to integrate

– Support specified php configuration file

– JIT global variables

– readline support (optional), terminal operation is more convenient

– Remote debugging, using java GUI

– Easy to operate (see help for details)

Install
In order to use phpdgb, you first need to download a php source code package. Then download the source code package of phpdgb and place it in the sapi directory of the php source code package. Finally, you can execute the installation command. The compilation and installation example is as follows:

Suppose we have downloaded the source code package of php and placed it in the /home/php directory.

#cd /home/php/sapi
#git clone https://github.com/krakjoe/phpdbg
#cd ../
#./buildconf --force
#./config.nice
#make -j8
#make install-phpdbg

Note:

1. If your php version is php5.6 or higher, phpdbg has been integrated into the php code package, and there is no need to download it separately.

2. Remember to add –enable-phpdbg in the compilation parameters.

3. The compile-time parameter, –with-readline can be optionally added. If you do not add it, phpdbg's history and other functions cannot be used.

Basic usage
1. Parameter introduction
phpdbg is a sapi of php, which can debug php from the command line. Commonly used parameters are as follows:

The following switches are implemented (just like cli SAPI):

-n ignore php ini

-c search for php ini in path

-z load zend extension

-d define php ini entry

The following switches change the default behavior of phpdbg:

-v disables quietness

-s enabled stepping

-e sets execution context

-b boring – disables use of color on the console

-I ignore .phpdbginit (default init file)

-i override .phpgdbinit location (implies -I)

-O set oplog output file

-q do not print banner on startup

-r jump straight to run

-E enable step through eval()

Note: passing -rr will cause phpdbg to quit after execution, rather than returning to the console

2. Common functions
We introduced the gdb tool before. In fact, the functions of phpdbg and gdb are very similar in some places. For example, you can set breakpoints, step through, etc. It's just that their debugging languages ​​are different. Gdb focuses on debugging c or c language, while phpdbg focuses on debugging php language. Below we will introduce some common debugging functions of phpdbg. The code to be debugged is as follows:

The source code of the file test_phpdbg_inc.php is as follows:

<&#63;php 
function phpdbg_inc_func()
{   
  echo "phpdbg_inc_func \n"; 
} 
&#63;>

The source code of the file test_phpdgb.php is as follows:

<&#63;php 
  include(dirname(__FILE__)."/test_phpdbg_inc.php"); 
  class demo{   
    public function __construct(){
       echo __METHOD__.":".__LINE__."\n";   
    }
    public function func($param){
       $param++;
       echo "method func $param\n";
    }
    public function __destruct(){
       echo __METHOD__.":".__LINE__."\n";
    }
  } 

 function func(){   
   $param = "ali";
   $param = $param + "baba";
   echo "function func $param\n";
 }

 $demo = new demo();
 $demo->func(1);
 func();
 phpdbg_inc_func();
&#63;>

3. Start phpdbg

After phpdbg is successfully installed, it will be in the bin directory of the installation directory. Enter the bin directory and enter phpdbg directly. As follows:

#phpdeg
[Welcome to phpdbg, the interactive PHP debugger, v0.4.0]
To get help using phpdbg type "help" and press enter
[Please report bugs to <http://github.com/krakjoe/phpdbg/issues>]
prompt>

To load the php script to be debugged, just execute the exec command. As follows:

#phpdbg
......
prompt> exec ./test_phpdbg.php

Of course we can also specify the e parameter when starting phpdbg. As follows:

#phpdbg -e ./test_phpdbg.php

4. View help information

If you have used other debugging tools before, you will find that phpdbg is similar to them. However, when you first use it, you will still often need to get help information. We can get help information through the help command.

......
prompt> help

phpdbg is a lightweight, powerful and easy to use debugging platform for PHP5.4+
It supports the following commands:

Information
 list   list PHP source
......

5. Set breakpoints

The command to set breakpoints is the same as gdb. They are all break, and the abbreviation is b. However, the specific command parameters are still different. Similar to gdb's breakpoint command, they can set breakpoints "by file name: line number" or line number. In addition, phpdbg also provides some methods for setting breakpoints specific to PHP. For example, set breakpoints based on opline, set breakpoints based on opcode, etc.

As we all know, PHP code is eventually parsed into opcode and then executed one by one by the PHP kernel. A PHP statement may be parsed into multiple opcodes. If we can set breakpoints by opcode, we can track the program execution process more accurately. Let's take a look at a specific example of setting breakpoints with phapdbg.

Set breakpoints by opline:

The opline mentioned here is the line number of the current code starting from the method entrance. For example, in the test_phpdgb.php file, the opline of the code "$param = $param "baba";" on line 18 is 2.

......
prompt> b func#2
prompt> r
demo::__construct:5
method func 2
[Breakpoint #0 resolved at func#2 (opline 0x7f5b230a2e38)]
[Breakpoint #0 resolved at func#2 (opline 0x7f5b230a2e38)]
[Breakpoint #0 resolved at func#2 (opline 0x7f5b230a2e38)]
[Breakpoint #0 in func()#2 at ./test_phpdbg.php:18, hits: 1]
>00018:   $param = $param + "baba";
 00019:   echo "function func $param\n";;
 00020: }
......

6. View breakpoints

Like gdb, phpdbg also uses the info break command to view breakpoints. An example is as follows:

....
prompt> info break
------------------------------------------------
File Breakpoints:
#1   /home/hailong.xhl/test_phpdbg.php:10
------------------------------------------------
Opline Breakpoints:
#0   7ff3219e1df0    (function breakpoint)
------------------------------------------------
Function opline Breakpoints:
#0   func opline 2
....

通过上面的显示,我们可以知道。info break的显示结果中会把断点的类型也给显示出来。#后面的数字是断点号。我们可以根据断点号删除断点。

7、删除断点

和gdb命令不一样。phpdbg的删除断点不是delete命令,而是break del 命令。示例如下:

......
prompt> break del 1
[Deleted breakpoint #1]
prompt>
......

break del 后面的数字1就是断点号。

8、查看代码

phpdbg查看代码的命令也是list。但是和gdb相比,使用的方式更多样一些。

显示指定函数的代码:

......
prompt> l f func
 00017:   $param = "ali";
 00018:   $param = $param + "baba";
 00019:   echo "function func $param\n";;
 00020: }
 00021:
prompt>
......

单步执行

phpdbg的单步执行只有一个命令 step。和gdb的step命令差不多。都是一行一行的执行代码。注意,phpdbg是没有next命令的。

....
prompt> s
[Breakpoint #0 resolved at func#2 (opline 0x152ba40)]
[L19      0x152ba70 ZEND_ADD_STRING     C2   @0  ./test_phpdbg.php]
>00019:   echo "function func $param\n";;
 00020: }
 00021:
....

继续执行

和gdb一样,phpdbg的继续执行命令也是continue,简写形式为c。

执行php代码

这个是phpdbg的一个特色。可以在调试的过程中使用ev命令执行任意的php代码。如:

......
prompt> ev $var = "val";
val
prompt> ev var_dump($var);
string(3) "val"
......

可以通过这种方式,在调试过程中动态的修改变量值,查看执行效果。

以上就是本文的全部内容,轻松玩转调试利器PHPDBG,希望大家喜欢。

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

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor