PHP – get calling file name and line number using debug_backtrace

Sometime it is useful to log the calling filename and line number details of the calling file/function in php. One common use case if to have a common logging function which logs calling filename detail for better debugging/troubleshooting. Here is an example.

File used for this example:

<?php
function f1() {
  $fileinfo = 'no_file_info';
  $backtrace = debug_backtrace();
  if (!empty($backtrace[0]) && is_array($backtrace[0])) {
    $fileinfo = $backtrace[0]['file'] . ":" . $backtrace[0]['line'];
  }
  echo "calling file info: $fileinfo\n";
}
?>

Here is example code and its outcome which uses util.php function f1().

<?php
require "util.php";
f1()
?>
calling file info: test.php:3
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments