user1897151
user1897151

Reputation: 503

include file(s) from another directory

Currently I am trying to include a PHP file from another directory.

public_html/a/class/test.php <-- from this file i would to include a file from
public_html/b/common.php <-- wanted to include this file

Not sure what I should do because I have tried using

dirname(__FILE__) 

and this keeps on returning public_html/a/ for me instead.

I have tried something like this

 dirname(__FILE__).'/../b/common.php'

but it does not help me in getting my file.

Upvotes: 1

Views: 144

Answers (3)

Ankit Pise
Ankit Pise

Reputation: 1259

include('../../b/common.php');

would include file for you, make sure both directory have same usergroup as user.

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173522

You can simply keep moving up the directory tree until you have the common ancestor:

require dirname(dirname(__DIR__)) . '/b/common.php';

The magic constant __DIR__ equals dirname(__FILE__), and was introduced in 5.3. Each use of dirname() goes back one directory, i.e.:

dirname('public_html/a/class'); // public_html/a
dirname('public_html/a'); // public_html

Btw, editors such as PhpStorm also understand this use of relative paths.

Upvotes: 3

jogesh_pi
jogesh_pi

Reputation: 9782

First of all i suggest you to define a variable for basepath and include that defined variable in relative files.

// This should be on any root directory file
define("PR_BASEPATH", dirname(__FILE__));

And according to your implementation, Assume you are in

public_html/a/class/test.php

and dirname(__FILE__) returns the directory name of the current file that always return the directory class according to test.php file.

And you want to include public_html/b/common.php that is on the other directory /b. So you have to get the document root directory first.

include $_SERVER['DOCUMENT_ROOT'] . "/b/common.php";

Take a look on $_SERVER['DOCUMENT_ROOT']

Upvotes: 0

Related Questions