Search code examples
phprelative-path

PHP relative link not working as expected


I'm struggling with a relative link to a .php file. The file contains my initialise code. It's working perfectly on the top-level pages but I just cannot connect on pages with a sub-folder. I have read and reread so many tutorials but can't get it to work.

<?php
  ob_start();
  try {
        require_once('./private/initialise.php');
        $years = YearsInBusiness();
?>

Folder Paths:

SiteFolder/private/initialise.php -- Location of file to link connect to.

SiteFolder/index.php ---Connects perfectly using path provided.

SiteFolder/fabrication/laser-cutting.php ---How do I reach initialise.php from laser-cutting.php file as nothing has worked?

I have tried:

'private/initialise.php'
'/private/initialise.php'
'./private/initialise.php'
'../private/initialise.php'
'./../private/initialise.php'
'../../private/initialise.php'
'../../../private/initialise.php'

+ Morse code!

Solution

  • Use dirname with the FILE magic constant. Using the second parameter for the dirname function you can specify how many levels you want to go "up".

    For example:

    require_once(dirname( __FILE__, 2) . "/your-folder/your-file.php");