barteloma
barteloma

Reputation: 6845

getting php working directory path

My file structure is here

-www
  -myAppDirectory
     -init
        -connect.php
     -products
        -api.php

products/api.php file will include the init/connect.php file like following.

<?php
 include_once("./connect.php");

users can call api.php from browser.

but it gives warning

Warning: include_once(./connect.php): failed to open stream

I try using this:

include_once($_SERVER["DOCUMENT_ROOT"] . "/connect.php");

but it gives warning,

Warning: include_once(D:\init\www/connect.php): failed to open stream

Upvotes: 0

Views: 65

Answers (4)

George G
George G

Reputation: 7695

I try to give more detailed answer.

For starters I'd like to mention what is __DIR__ it's one of PHP: Magic constants

It contains the path of the directory in which your current script is executed. In your case, something similar to: D:\init\www\myAppDirectory\products without ending slash (on windows)/back-slash (linux, etc.)

So for example __FILE__ would give you D:\init\www\myAppDirectory\products\api.php

Now if you want to include file from relatively closer directory, I'd prefer to use:

include_once("../init/connect.php");

(maybe not required but) Also it's good practice to use DIRECTORY_SEPARATOR

include_once(".." . DIRECTORY_SEPARATOR . "init". DIRECTORY_SEPARATOR ."connect.php");

You can also use dirname($path) function:

$myAppDir = dirname(__DIR__); // D:\init\www\myAppDirectory
include $myAppDir . DIRECTORY_SEPARATOR . "init". DIRECTORY_SEPARATOR ."connect.php"

Also include can be faster than include_once because the last one have to check first over the included files.

Why is require_once so bad to use?

Upvotes: 0

xdazz
xdazz

Reputation: 160833

Using absolute path is always good (clean and solid).

include_once(__DIR__ . "/../init/connect.php");

Upvotes: 2

Jenz
Jenz

Reputation: 8369

include_once("./connect.php");

will check for a file outside the parent directory ie., outside products and there is no any file connect.php outside it. You have to use

include_once("../init/connect.php");

Upvotes: 1

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

try ../ for out the products dir then add path connect.php

include_once("../init/connect.php");

you can also use (not tested) ./ for root

include_once("./init/connect.php");

Upvotes: 1

Related Questions