0

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
Svante
  • 45
  • 1
  • 11
  • Have you tried passing the full path to `log.txt` when using `file_put_contents`? e.g. `file_put_contents(__DIR__ . '/../src/log.txt', $towrite, FILE_APPEND);` – Ankh May 21 '15 at 17:54

1 Answers1

0

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);
Roelof
  • 45
  • 7
  • Are you sure you have permissions to write in the directory and does the target directory (`src`) exist? You can use `is_writeable` to check if the file can be created. You may also want to check if there is any `open_basedir` restriction, which might block you from accessing the file. – Roelof May 21 '15 at 18:24
  • Apparently it isn't writeable... So I need to chmod it? To what? – Svante May 21 '15 at 18:28
  • You could chmod it to 0777, or somehow take ownership and then just chmod it to 0755. – Roelof May 21 '15 at 18:41