16

I have some problems with the relative and absolute paths in php fopen. I have the following directories:

project:
    scripts:
        myscript.php
    logs:
        mylog.log

I want to open mylog.log from myscript.php and I don't know how to specify the path. I tried

fopen('../logs/mylog.log', "a")

but it won't work. Thanks.

LE: Thanks for you answers.

user1552480
  • 207
  • 1
  • 3
  • 8

3 Answers3

39

In php, there are a couple of global constants that could be of help to you. Namely, __DIR__ gives you the directory of the current file ('.' just gives you the directory of the root script executing).

So what you want is:

fopen(__DIR__ . '/../logs/mylog.log', "a")
Jeremy Blalock
  • 2,538
  • 17
  • 23
  • Indeed. `dirname(__FILE__)` can be used for portability to PHP installations under 5.3.0. – TaZ Mar 16 '13 at 15:31
8

You can use $_SERVER['DOCUMENT_ROOT'] which gives the document root of the virtual host.

eg: $_SERVER['DOCUMENT_ROOT']."/log/mylog.log"

Can Geliş
  • 1,454
  • 2
  • 10
  • 19
8

This should work:

fopen(__DIR__ . '/../logs/mylog.log', "a");

or in PHP < 5.3:

fopen(dirname(__FILE__) . '/../logs/mylog.log', "a");
Brandon
  • 16,382
  • 12
  • 55
  • 88