phpob-start

Why inside ob_start file_put_contents is nowhere to be found?


I really need to use ob_start with PHP in my code. So I have this:

ob_start("function123");

So inside function "function123" I have this:

file_put_contents("aaa.txt","xxxx");

However I cant find this file anywhere. The PHP script has 777 permission and file_put_contents is working just fine cause when I use it oustide of "function123" it works perfectly and the file appears right in the same path as the PHP script.

HOWEVER if I do this

file_put_contents("/main/folder/aaa.txt","xxxx");

It works. So does ob_start uses a different scope/path to create files? The strange thing is that if I use file_get_contents with relative paths it works exactly as exepected: the path is relative from the current PHP script path.


Solution

  • The ob_start function may change the working directory of the PHP process when it invokes the user-defined callback. This is documented in the manual:

    Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.

    You can work around this by obtaining either the script path or document root and changing the working directory yourself using chdir().

    I don't know for certain if this is the problem since when I test using Apache 2.4 everything seems to work as expected (i.e. no directory changing in the callback). Anyway, you might consider doing something like this instead, opening the file outside of the callback while the PHP process's PWD is still good:

    <?php
    
    $handle = fopen('output.txt','w');
    $callback = function($buffer, $phase) use($handle) {
        fwrite($handle,$buffer);
        return '';
    };
    
    ob_start($callback);
    echo 'Hello, World!' . PHP_EOL;
    ob_end_flush();
    fclose($handle);