save var_dump into text file

save var_dump into text file

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Redirecting var_dump Output to Text Files in PHP

When debugging database connections or executing raw SQL queries, developers often rely on var_dump() for immediate visual feedback. In your specific case, you are successfully connecting to MySQL and listing available databases using the mysql_query function, but the output is currently rendering directly in the browser. If you need to capture this structured data—specifically the array structure returned by var_dump()—into a file for later analysis or logging, you must explicitly redirect the output stream.

The standard approach to achieve this is by utilizing PHP's output buffering functions, specifically ob_start(), ob_get_contents(), and ob_end_flush(). This method allows you to intercept the content that would otherwise be sent to the browser before it reaches the client. However, applying this logic requires careful placement of these functions relative to your var_dump calls.

Implementing Output Buffering for var_dump

To save the var_dump output into a file named test.txt, you must wrap the code block that generates the debug information within an output buffering context. Here is how you can modify your existing logic:

<?php
$server = "127.0.0.1";
$username = "root";
$password = "1";

function connecttodb($server, $username, $password) {
    // Start output buffering to capture subsequent output
    ob_start();
    
    if (mysql_connect("$server", "$username", "$password", TRUE)) {
        echo "Connected successfully to >> " . $server;
        
        $result = mysql_query('SHOW DATABASES');
        
        while ($row = mysql_fetch_array($result)) {
            var_dump($row); 
        }
        
        // Retrieve the contents of the buffer
        $dumpContents = ob_get_contents();
        
        // End output buffering to send remaining output to browser (optional)
        ob_end_flush();
        
        // Write the captured dump to a file
        $fileHandle = fopen("test.txt", "a"); // 'a' appends, use 'w' to overwrite
        if ($fileHandle) {
            fwrite($fileHandle, $dumpContents);
            fclose($fileHandle);
            
            // Optional: Clear the buffer so it doesn't appear in browser twice if ob_end_flush is used later
            ob_clean(); 
        }
        
        return true;
    } else {
        return false;
    }
}

connecttodb($server, $username, $password);
?>

Understanding the Stream Mechanics

The core mechanism here relies on ob_start(), which tells PHP to buffer all subsequent output. When var_dump executes, it writes to the internal buffer rather than directly to the HTTP response stream. By calling ob_get_contents(), you extract that buffered string as a variable. Finally, fopen and fwrite allow you to persist that string to your file system.

There is a critical distinction regarding the mode used in fopen. In your original code, you used "ab". This mode attempts to open the file for appending in binary mode. While valid on some systems, it can behave unpredictably depending on how the underlying filesystem handles text encoding versus raw bytes. For standard logging of text-based debug output like var_dump, using "a" (append) or "w" (write/overwrite) is generally safer and more predictable across different server environments.

Legacy Functionality and Modern Context

It is important to note that your code relies on the mysql_* extension, which was deprecated in PHP 5.5 and removed in PHP 7.0. If you are working on a legacy system, this approach remains valid. However, if you are maintaining or starting new projects, migrating to mysqli or PDO is strongly recommended.

In modern PHP development, output buffering strategies often change based on the framework being used. For instance, if you were building an application with Laravel, the framework manages output buffering and rendering internally. Directly appending debug dumps to files from within a controller or route can sometimes conflict with Laravel's response handling or view rendering cycles. In such scenarios, using the storage/logs directory via a dedicated logging channel configured in config/logging.php is the preferred pattern over manually managing text files for debugging data.

Potential Pitfalls and Best Practices

When implementing this solution, be aware of performance implications. Buffering every request can increase memory usage, especially if large amounts of data are being dumped. Additionally, appending to a log file without timestamps can make debugging difficult later on, as you lose context regarding when specific database errors or schema listings occurred. A production-ready logger would typically include the current timestamp and a unique identifier within each entry.

Finally, ensure that your script has write permissions for the directory containing test.txt. If the web server user (often www-data or apache) lacks permission to write to that specific folder, the fwrite function will fail silently or throw a warning, leaving you without the log data you intended to capture.

Our network