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.
Recognizing different error types in PHP
The most effective debugging tools
Catching and handling errors
Professional debugging techniques
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.
Recognizing different error types speeds up the resolution process
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.
<?php
// Noktalı comma eksik
$name = "John"
echo "Merhaba " . $name;
// Yanlış parantez kapama
if($x > 5) {
echo "x 5'ten large";
?>
<?php
// Noktalı comma eklendi
$name = "John";
echo "Merhaba " . $name;
// Parantez kapatıldı
if($x > 5) {
echo "x 5'ten large";
}
?>
These are errors that occur while running the code. Even though the syntax is correct, it occurs during runtime and often halts code execution.
<?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;
?>
<?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';
?>
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.
<?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";
}
?>
<?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";
}
?>
These are notifications that do not stop your code from running, but indicate potential issues or areas for improvement that are important for optimization.
<?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();
?>
<?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();
?>
Methods for quickly and effectively detecting and resolving errors.
var_dump() FonksiyonuDisplays 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() FonksiyonuDisplays 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() FonksiyonuDisplays 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();
?>
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
*/
?>
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();
}
?>
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();
?>
Xdebug is a powerful PHP extension offering advanced debugging features such as step-by-step execution, variable inspection and code-coverage 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
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");
?>
Professional tips that will make your debugging process more efficient.
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.
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.
"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.
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 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.
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 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 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.
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.