Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write the path in php fopen?

Tags:

path

php

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.

like image 410
user1552480 Avatar asked Mar 16 '13 15:03

user1552480


3 Answers

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")
like image 61
Jeremy Blalock Avatar answered Nov 07 '22 04:11

Jeremy Blalock


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

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

like image 32
Can Geliş Avatar answered Nov 07 '22 04:11

Can Geliş


This should work:

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

or in PHP < 5.3:

fopen(dirname(__FILE__) . '/../logs/mylog.log', "a");
like image 37
Brandon Wamboldt Avatar answered Nov 07 '22 03:11

Brandon Wamboldt