Monitoring PHP Applications with php-ast and xhprof Libraries

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is PHP application monitoring and why is it needed?

PHP application monitoring is the process of collecting, analyzing, and visualizing performance metrics, errors, and resource usage of web applications written in PHP. Without monitoring, it is impossible to identify bottlenecks, memory leaks, slow database queries, or suboptimal code. Key libraries for this are xhprof (profiling) and php-ast (syntax tree analysis).

How to install?

To install xhprof (profiling extension), run:

pecl install xhprof

Add to php.ini:

extension=xhprof.so

For php-ast (AST analysis):

pecl install ast

Then include it via composer:

composer require phpunit/php-code-coverage

Main features

  • Request profiling — xhprof collects data on execution time, function call counts, and memory usage.
  • Syntax analysis — php-ast allows parsing PHP code into an abstract syntax tree for static analysis.
  • Error monitoring — integration with Sentry or Monolog for logging exceptions.
  • Performance metrics — response time, requests per second (RPS), CPU/RAM usage.

PHP code example

<?php// Profiling with xhprofxhprof_enable();

// Your application code$result = someHeavyFunction();

$xhprofData = xhprof_disable();include_once '/path/to/xhprof_lib/utils/xhprof_lib.php';include_once '/path/to/xhprof_lib/utils/xhprof_runs.php';$xhprofRuns = new XHProfRuns_Default();$runId = $xhprofRuns->save_run($xhprofData, 'my_app');echo 'Profiler run ID: ' . $runId;

// AST analysis with php-ast$code = file_get_contents('index.php');$ast = ast\\parse_code($code, $version = 70);echo ast\\get_kind_name($ast->kind);?>

When to use?

Monitoring is necessary in a production environment to track performance degradation after releases, during load testing, and also for finding memory leaks in long-running processes (e.g., in queues or WebSocket servers). The xhprof and php-ast libraries are ideal for integration into CI/CD pipelines and observability systems (Prometheus, Grafana).

Conclusion

Using profilers and static analyzers is a mandatory practice for maintaining high quality in PHP applications. Start by installing xhprof and php-ast to get a complete picture of how your code works.

Recommendations