Search code examples
phpfopenfwritefile-put-contents

Php writing string to file in ../src


So I'm trying to get my php script append a text to log.txt, log.txt is placed in src/log.txt and the php script in web/script.php (they have other names but well...) So I've tried:

$logfile1 = fopen('log.txt', 'a', [$use_include_path = TRUE]);
$towrite = date('l jS \of F Y h:i:s A').': '.$var1.' did '.$var2.' and '.$var3.'\n';
fwrite($logfile1, $towrite);

Wich didn't work... (i can echo $towrite and get a valid result) Note that in the top of the file

set_include_path("../src/" . PATH_SEPARATOR . get_include_path());

is done.

So... I continued with trying:

file_put_contents('log.txt', $towrite, FILE_APPEND | FILE_USE_INCLUDE_PATH);

Instead of fwrite... It didnt work either... Even trying to put log.txt in web/ and having

file_put_contents('log.txt', $towrite, FILE_APPEND);

So now I'm turning to the masters ;) how do I write that string to the file src/log.txt from web/script.php?

The file tree:

| - web
| | - script.php
| - src
| | - log.php

Solution

  • You may indeed use absolute paths here.

    Say your file structure looks something like this:

    |- src
    |  |- log.txt
    |-source
       |- code.php
    

    Then we'd perform the following code to go one dir up, ignoring any include_dir setting currently active.

    <?php
    $log = dirname(__FILE__) . "/../src/log.txt";
    
    $date = date('l jS \of F Y h:i:s A');
    $write = "{$date}: {$var1} did {$var2} and {$var3}\n";
    
    file_put_contents($log, $write, FILE_APPEND);