PHP Dynamic include based on current file path

前端 未结 4 2037
北海茫月
北海茫月 2021-02-04 09:59

I want to find a method to include some files based on the current file path.. for example:

I have \"website.com/templates/name1/index.php\", this \"index.php should be

相关标签:
4条回答
  • 2021-02-04 10:14

    I'd just do something as simple as:

    $dir = str_replace('website.com/','website.com/content/',__DIR__);
    include "$dir/content.php";
    

    And your HTTP wrapper issue doesn't seem to have anything to do with this. What do you mean by overrun it? You generally never want to do a remote include.

    0 讨论(0)
  • 2021-02-04 10:17

    You can place your includes inside conditional logic.

    <?php   
    if (isset($_GET['service'])) {
        include('subContent/serviceMenu.html');
    } else if (isset($_GET['business'])) {
        include('subContent/business_menu.html');
    } else if (isset($_GET['info'])) {
        include('subContent/info_menu.html');
    }
    else {
        include('subContent/banner.html');
    }
    ?>
    <a href="http://localhost/yourpage.php?service" />
    
    0 讨论(0)
  • 2021-02-04 10:28

    Why not do it in the simple way:

    dirname(__FILE__); //Current working directory
    dirname(dirname(__FILE__)); //Get path to current working directory
    

    And then finally

    $include_path = $dir_path . 'file_to_include.php';
    include $include_path;
    
    0 讨论(0)
  • 2021-02-04 10:29

    I think you need to use __FILE__ (it has two underscores at the start and at the end of the name) and DIRECTORY_SEPARATOR constants for working with files based on the current file path.

    For example:

    <?php
      // in this var you will get the absolute file path of the current file
      $current_file_path = dirname(__FILE__);
      // with the next line we will include the 'somefile.php'
      // which based in the upper directory to the current path
      include(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'somefile.php');
    

    Using DIRECTORY_SEPARATOR constant is more safe than using "/" (or "\") symbols, because Windows and *nix directory separators are different and your interpretator will use proper value on the different platforms.

    0 讨论(0)
提交回复
热议问题