Search code examples
phpinclude-pathgetcwd

PHP getcwd() function to be used with include or require in different directories


I need to include a path from a config file in one directory on other scrpits a few directories up or down.

My config file has a function like this:

$execute_path = getcwd() . "/execute.php";

The execute.php file resides in the same directory as the config file wich makes it ok and the output will become:

public-html/config-directory/execute.php

Now if use the same function in a directory that is outside of the original directory, it treats the getcwd() function as if it was in that directory.

For example, if call it from a directory public-html/one/two/three/somefile.php as follow:

<?php 
include(pathto/config.php)
echo $execute_path;
?>

The output becomes publichtml/one/two/three/execute.php rather than staying publichtml/config-directory/execute.php

How can I achieve what I want here? Sorry for the long explanation. Thanks.


Solution

  • Include can be very tricky why i advice is

    //config.php
    
    define("SITE_PATH", "public-html/config-directory");
    
    
    //execute.php
    
    $execute_path =SITE_PATH . "/execute.php";
    
    //run.php
    include_once 'config.php';
    include_once 'execute.php';
    
    echo $execute_path;