0

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
barteloma
  • 6,403
  • 14
  • 79
  • 173

4 Answers4

2

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

include_once(__DIR__ . "/../init/connect.php");
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

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");
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
1
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");
Jenz
  • 8,280
  • 7
  • 44
  • 77
0

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?

Community
  • 1
  • 1
George G
  • 7,443
  • 12
  • 45
  • 59