Arama Yap Mesaj Submit
Request a Callback
+90
X
X

Select Your Currency

Turkish Lira $ US Dollar Euro
X
X

Select Your Currency

Turkish Lira $ US Dollar Euro

Contact Us

Location Halkali merkez neighborhood fatih st ozgur apt no 46 , Kucukcekmece , Istanbul , 34303 , TR

PHP'de Debugging
Techniques and Examples

How do you detect and fix errors in your code? Learn debugging techniques, tools, and best practices to solve problems you may encounter in your projects.

Error
Types

Recognizing different error types in PHP

Debugging
tools

The most effective debugging tools

Error
Management

Catching and handling errors

Best
Uygulamalar

Professional debugging techniques

What is Debugging?

One of the most important stages of the software development process

Debugging is the process of finding, understanding and fixing errors in your code during the software development process.

Every software developer encounters various errors in their projects. These errors can sometimes be simple typos, sometimes logical errors, or sometimes more complex system problems. Debugging is a systematic approach to help you solve these problems.

Information: The term "Debug", II. It entered computer terminology during World War II. Grace Hopper, who was working on the Mark II computer at Harvard University, coined the term "debugging" when she found an actual bug inside the machine and removed it.

Why Is Debugging Important?

  • Quality Code: Code free of errors is more reliable and maintainable.
  • Zaman Tasarrufu: Regular debugging prevents bigger problems in the future.
  • Problem Solving Skills: Debugging improves your problem-solving abilities.
  • Code Understanding: As you fix bugs, you gain a better understanding of how your code works.
  • User Experience: Bug-free applications provide users with a better experience.
Without Debugging
  • unexpected crashes
  • Data loss risks
  • User dissatisfaction
  • vulnerabilities
  • maintenance difficulty
With Active Debugging
  • Reliable application
  • Quick problem solving
  • User satisfaction
  • More secure code
  • Easy maintenance and development

Error Types in PHP

Recognizing different error types speeds up the resolution process

Syntax Errors (Parse Errors)

These are problems caused by grammatical errors in your PHP code. Such errors are detected by PHP before your code is executed and the code stops completely.

Common Causes:
  • Missing or extra parentheses, semicolons
  • Incorrect syntax structures
  • Incorrect use of quotation marks
  • Misuse of PHP tags
Erroneous Code Example
<?php
// Noktalı comma eksik
$name = "John"
echo "Merhaba " . $name;

// Yanlış parantez kapama
if($x > 5) {
  echo "x 5'ten large";
?>
Correct Code
<?php
// Noktalı comma eklendi
$name = "John";
echo "Merhaba " . $name;

// Parantez kapatıldı
if($x > 5) {
  echo "x 5'ten large";
}
?>

Runtime Errors

These are errors that occur while running the code. Even though the syntax is correct, it occurs during runtime and often halts code execution.

Common Causes:
  • Calling undefined functions or classes
  • Including files that do not exist
  • Calling a function with missing parameters
  • Attempts to divide by zero
Erroneous Code Example
<?php
// Undefined fonksiyon çağrısı
calculateTotal($price, $quantity);

// Olmayan bir file dahil etme
include 'non_existent_file.php';

// Sıfıra bölme errorsı
$result = 10 / 0;
?>
Correct Code
<?php
// Fonksiyonu tanımlama
function calculateTotal($price, $quantity) {
  return $price * $quantity;
}
$total = calculateTotal($price, $quantity);

// Dosyanın varlığını kontrol etme
if(file_exists('config.php')) {
  include 'config.php';
}

// Sıfıra bölmeyi kontrol etme
$divisor = 0;
$result = ($divisor != 0) ? (10 / $divisor) : 'Sıfıra bölünemez';
?>

Logic Errors

These are errors that, although the code works syntactically correctly, does not produce the expected result. These are the hardest errors to detect because PHP does not recognize them as errors.

Common Causes:
  • Incorrect algorithm or business logic
  • Incorrect conditionals
  • Incorrect determination of cycle boundaries
  • Incorrect assignment of variable values
Erroneous Code Example
<?php
// Sonsuza giden döngü
$i = 1;
while($i > 0) {
  echo $i;
  $i++;  // i her zaman 0'dan large olacak
}

// Yanlış karşılaştırma operatörü
$age = 20;
if($age = 18) {  // Atama yapılıyor, karşılaştırma değil!
  echo "Yaşınız 18";
}
?>
Correct Code
<?php
// Correct döngü sınırı
$i = 1;
while($i <= 10) {  // 10'a kadar sayar
  echo $i;
  $i++;
}

// Doğru karşılaştırma operatörü
$age = 20;
if($age == 18) {  // Eşitlik karşılaştırması
  echo "Yaşınız 18";
}
?>

Warnings and Notices (Warnings & Notices)

These are notifications that do not stop your code from running, but indicate potential issues or areas for improvement that are important for optimization.

Types:
  • E_WARNING: Serious, but non-blocking errors
  • E_NOTICE: Notifications indicating possible errors or unexpected behavior
  • E_DEPRECATED: Usage of features that will not be supported in future PHP versions
  • E_STRICT: Best Practice Recommendations
Warning/Notification Examples
<?php
// E_NOTICE: Undefined değişken kullanımı
echo $undefined_var;

// E_WARNING: Olmayan dosya dahil etme
include 'missing_file.php';

// E_DEPRECATED: Usagedan kaldırılmış fonksiyon
mysql_connect('localhost', 'user', 'pass');

// E_STRICT: Statik olmayan metodu statik as çağırma
class Test {
  function method() {}
}
Test::method();
?>
Optimized Code
<?php
// Değişken control
$undefined_var = '';
echo $undefined_var;

// Dosya control
if(file_exists('config.php')) {
  include 'config.php';
}

// Güncel fonksiyon kullanımı
$conn = new mysqli('localhost', 'user', 'pass');

// Correct sınıf metodu çağrısı
class Test {
  static function method() {}
}
Test::method();
?>

PHP Debugging Techniques

Methods for quickly and effectively detecting and resolving errors.

Basic Debugging Tools

var_dump() Fonksiyonu

Displays the contents and structure of the variable in detail. Shows data type, length and value information.

<?php
// Basit bir değişken
$name = "Ahmet";
var_dump($name);
// Çıktı: string(5) "Ahmet"

// Dizi
$user = [
  "id" => 1,
  "name" => "Ahmet",
  "age" => 30,
  "active" => true
];
var_dump($user);
// Tüm dizi yapısını ve içeriğini gösterir

// Nesne
$obj = new stdClass();
$obj->name = "Test";
$obj->value = 123;
var_dump($obj);
// Nesnenin türünü ve specialliklerini gösterir
?>

print_r() Fonksiyonu

Displays the contents of the variable in a more readable format. To assign the output to a variable, true can be used as the second parameter.

<?php
// Dizi örneği
$colors = ["red", "green", "blue"];
print_r($colors);
/* Çıktı:
Array
(
    [0] => red
    [1] => green
    [2] => blue
)
*/

// Çıktıyı değişkene atama
$output = print_r($colors, true);
echo htmlspecialchars($output); // Secure HTML output

// İç içe dizileri okunabilir formatta gösterir
$complex = [
  "users" => [
    ["name" => "Ali", "role" => "admin"],
    ["name" => "Ayşe", "role" => "editor"]
  ]
];
print_r($complex);
?>

debug_backtrace() Fonksiyonu

Displays the call stack. By viewing which functions are called in what order, you can follow the flow of the code.

<?php
function first() {
  second();
}

function second() {
  third();
}

function third() {
  // Çağrı yığınını al
  $trace = debug_backtrace();
  echo "Çağrı Yığını:\n";
  foreach ($trace as $level => $call) {
    echo "#$level: ";
    if (isset($call['class'])) {
      echo $call['class'] . '::';
    }
    echo $call['function'] . '()';
    if (isset($call['file'])) {
      echo ' çağrıldı: ' . $call['file'] . ', line: ' . $call['line'];
    }
    echo "\n";
  }
}

// Çağrı zincirini başlat
first();
?>

PHP Error Reporting Settings

Settings that control which PHP errors are displayed. It is useful in the development process to see all errors.

<?php
// Tüm errorları göster (development ortamı for)
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Sadece belirli error türlerini göster
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Errorları gizle (canlı ortam for)
error_reporting(0);
ini_set('display_errors', 0);

// Errorları loglama
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');

// PHP.ini üzerinden yapılandırma
/*
error_reporting = E_ALL
display_errors = On
log_errors = On
error_log = /path/to/error.log
*/
?>

Error Catching and Handling

try-catch Blocks

Structures that catch and handle potential errors to prevent the application from crashing. They provide error management through exceptions.

<?php
// Temel try-catch kullanımı
try {
  // Potansiyel as error verebilecek kod
  $file = fopen('dosya.txt', 'r');
  if (!$file) {
    throw new Exception("Dosya açılamadı!");
  }
  $content = fread($file, filesize('dosya.txt'));
  fclose($file);
} catch (Exception $e) {
  // Error yakalandı ve işlendi
  echo "Error mesajı: " . $e->getMessage();
  // Alternatif as logla
  error_log("Dosya errorsı: " . $e->getMessage());
} finally {
  // Her durumda çalışacak kod
  echo "Worklem tamamlandı.";
}

// Çoklu catch blokları
try {
  $db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
  $stmt = $db->query("SELECT * FROM non_existent_table");
} catch (PDOException $e) {
  // Veritabanı errorlarını yakala
  echo "Veritabanı errorsı: " . $e->getMessage();
} catch (Exception $e) {
  // Other all errorları yakala
  echo "Genel error: " . $e->getMessage();
}
?>

Custom Error Handlers

You can change PHP's default error behavior by defining your own error handling functions.

<?php
// Special error işleyicisi tanımlama
function customErrorHandler($errno, $errstr, $errfile, $errline) {
  $error_type = "";
  switch ($errno) {
    case E_ERROR:
      $error_type = "Error";
      break;
    case E_WARNING:
      $error_type = "Warning";
      break;
    case E_NOTICE:
      $error_type = "Bildirim";
      break;
    default:
      $error_type = "Bilinmeyen";
      break;
  }

  // Error mesajını create
  $error_message = "[$error_type] $errstr in $errfile on line $errline";

  // Error logla
  error_log($error_message);

  // Userya daha kullanıcı dostu bir mesaj göster
  if ($errno == E_ERROR) {
    echo "
Bir error oluştu. Please daha sonra tekrar deneyin.
"; die(); // Kritik errorlarda çalışmayı durdur } else { echo "
Bir sorun oluştu, ancak işleme devam ediliyor.
"; } // true döndürerek PHP'nin kendi error işleyicisini çalıştırmasını engelle return true; } // Special error işleyicisini ayarla set_error_handler("customErrorHandler"); // Şimdi bir error createalım echo $undefined_variable; // E_NOTICE üretecek // Workleyiciyi varsayılana sıfırla restore_error_handler(); ?>

Advanced Debugging Techniques

Xdebug Extension

Xdebug is a powerful PHP extension offering advanced debugging features such as step-by-step execution, variable inspection and code-coverage analysis.

Xdebug requires additional installation in your XAMPP or other PHP environments.
Features offered by Xdebug:
  • Step-by-step code execution (step debugging)
  • Enhanced var_dump() output
  • Detailed error reports
  • Code Scope Analysis
  • Profiling and performance analysis
# Xdebug yapılandırma örneği (php.ini)
[xdebug]
zend_extension=xdebug
xdebug.mode=develop,debug
xdebug.start_with_request=yes
xdebug.client_host=127.0.0.1
xdebug.client_port=9003
xdebug.idekey=VSCODE
xdebug.log=/path/to/xdebug.log

Log Usage

Logging is an effective way to monitor your application's behavior and diagnose issues. You can use PHP's error_log() function or custom logging libraries.

<?php
// Temel error_log kullanımı
function logMessage($message, $level = 'INFO') {
  error_log("[$level] " . date('Y-m-d H:i:s') . " - $message");
}

// Örnek kullanım
logMessage("Uygulama başlatıldı");
try {
  $db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
  logMessage("Veritabanı bağlantısı kuruldu");
} catch (PDOException $e) {
  logMessage("Veritabanı bağlantı errorsı: " . $e->getMessage(), 'ERROR');
}

// Farklı log seviyelerini kullanma
function debug($message) { logMessage($message, 'DEBUG'); }
function info($message) { logMessage($message, 'INFO'); }
function warning($message) { logMessage($message, 'WARNING'); }
function error($message) { logMessage($message, 'ERROR'); }

// Değişken değerlerini loglama
$user_id = 123;
debug("User ID: $user_id");

// Worklem süresini loglama
$start_time = microtime(true);
// ... işlem yapılıyor ...
$end_time = microtime(true);
$execution_time = ($end_time - $start_time) * 1000; // milisaniye
info("Worklem tamamlandı. Süre: {$execution_time}ms");
?>

Best Practices and Tips

Professional tips that will make your debugging process more efficient.

Adopt a Systematic Approach

Isolate errors systematically, not randomly. Isolate the problem, develop hypotheses, test them, and evaluate the results. The scientific method is also effective in error debugging.

Keep asking the question 'why' until you get to the root of the problem. Often, the apparent problem is a symptom of another underlying issue.

Make Incremental Changes

Instead of making multiple changes at once, make one change and observe the results. This approach helps you determine which change solved the issue or introduced new problems.

Use a version control system like Git to record every change. This way, you can revert to the previous working version if needed.

Explain Your Code

"Rubber Duck Debugging" is a technique where you explain your code line by line (even to a toy duck) to clarify your thought process and help identify logical errors.

Ask another programmer to review your code. A fresh perspective can quickly spot issues you might have missed.

Implement Effective Logging

Keep comprehensive and meaningful logs. Not only errors, but also important flow points, variable values, and system statuses should be logged. A good logging strategy allows you to quickly diagnose issues.

Add contextual information such as timestamp, file/line information, and operation ID to your log messages. This information can be very valuable when solving complex issues.

Write Your Code Modularly

Write small, independent, and testable functions. Modular code makes it easier to isolate issues and simplifies the debugging process.

A function should have a single responsibility. Break functions that do multiple tasks into smaller, focused ones.

Run Pre-Checks

Check the parameters and input values in your functions before processing. Early detection of unexpected values significantly simplifies the debugging process.

Use type hinting (PHP 7.0 and later). This feature automatically generates an error when wrong type values are sent.

Write Automated Tests

Write unit tests and integration tests to regularly test your code. Automated tests ensure that the functionality is not affected by changes.

Adopt the Test-Driven Development (TDD) approach: Write tests first, then write code. This approach helps you produce more reliable and testable code.

Use the Right Tools

Use professional development tools such as Xdebug, PHPUnit, PHP CodeSniffer and PhpStorm. They significantly speed up finding and fixing errors.

Learn about the debugging features of your IDE. Breakpoints, step-by-step execution, and variable tracking are very valuable.

The Most Important Point to Remember.

Debugging is a natural part of the software development process. Errors are not failures, but opportunities for learning and improvement. With a systematic approach, the right tools, and continuous practice, you can improve your debugging skills over time.

Top