Jump to content

Include path to path of file


mrbean

Recommended Posts

Hello there,

 

I think its an easy question to answer but I don't know the answer myself :P

 

Question:

 

I have for example 3 files:

 

index.php (in root directory)

test.php(in 'includes' directory)

test2.php(in 'includes' directory)

 

The script looks like this:

 

Index.php

<?php

include("includes/test.php");
?>

 

test.php

<?php
include("test2.php");
?>

 

test2.php

class
function
class
class
something
etc.
Just some code

 

Now when I include test.php in index.php,

test.php will think I want to include an file in the root directory(where index.php also is)

But I want to include the file where test.php and test2.php both are("includes"  directory/path).

So include path to path of file.

 

How can I do that?

 

I hope u understand me (I speak bad english) :)

Link to comment
Share on other sites

since the folder is called 'includes' I'm assuming the files in there are always pulled out by another file in the root directory and never actually executed from there they reside.

 

you can simply use

include('includes/test2.php');

in test.php

 

 

Link to comment
Share on other sites

To elaborate,

 

include() and friends include files relative to the current working directory. In 99% of cases that's the directory with the PHP script that first executed - not the directory with the script executing at that moment (ie, the one with the include()).

Two easy ways to make sure you include the right files involve using absolute paths:

// relative to the root of the website
include $_SERVER["DOCUMENT_ROOT"] . "/includes/test2.php";

// relative to the current file
include __DIR__ . "/test2.php"; // PHP 5.3+ only
include dirname(__FILE__) . "/test2.php";

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.