, 2 min read

XHProf with NGINX

XHProf is a PHP profiler. I had written on XHProf here:

  1. Profiling PHP Programs
  2. Profiling PHP Programs #2

XHProf was originally written by Facebook engineers. Even though it severely slows down your PHP program during execution, it is nevertheless a valuable tool to get an understanding, where your PHP program is spending its time.

Once XHProf has generated its data after running your PHP program, you want to see the reports on the data. One easy approach is to use the builtin web-server into PHP:

php -S 0:8000 -t /usr/share/webapps/xhprof/xhprof_html

This will start a web-server at port 8000. In the browser type something like below into the URL field:

http://localhost/index.php?run=66fbf551c7dca&source=saaze

This should show you the report of your run.

This post is about using NGINX to see the report, instead of the builtin web-server of PHP itself. The naive approach by just using the default does not work.

1. Changing directory for XHProf output. By default XHProf uses sys_get_temp_dir() to find the temporary directory. On Arch Linux this is /tmp. That needs to be changed. First, create /srv/http/tmp. Second, edit php.ini.

extension=xhprof
xhprof.output_dir = /srv/http/tmp

2. Symbolic link. XHProf contains a number of PHP programs and JavaScript files. Create a symbolic link under the web-server root:

ln -s /usr/share/webapps/xhprof/xhprof_html xhprof

3. Activate PHP in NGINX. That has probably already been done. Nevertheless, it is repeated here.

location ~ \.php$ {
    try_files $fastcgi_script_name =404;

    # default fastcgi_params
    include fastcgi_params;

    # fastcgi settings
    fastcgi_pass                        unix:/run/php-fpm/php-fpm.sock;
    #fastcgi_index                      index.php;
    fastcgi_buffers                     8 16k;
    fastcgi_buffer_size         32k;

    # fastcgi params
    fastcgi_param DOCUMENT_ROOT $realpath_root;
    fastcgi_param SCRIPT_FILENAME       $realpath_root$fastcgi_script_name;

    fastcgi_cache_bypass $no_cache;
    fastcgi_no_cache $no_cache;
}

The location section is the third in the hierarchy:

# http ## server ### location ### ... ## server ## ...

4. Result. Your reports are now here:

http://localhost/xhprof/index.php?run=66fbf551c7dca&source=saaze

It looks like this:


XHProf: Hierarchical Profiler ReportNo XHProf runs specified in the URL.
Existing runs:

5. AUR package. I maintain an AUR package: XHProf.