Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Dynamic include based on current file path

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 a unique file that I will use in many different directories on different depths, so I want to make the code universal so I don't need to change anything inside this file..

So if this "index.php" is located in

"website.com/templates/name1/index.php"

than it should include the file located here:

"website.com/content/templates/name1/content.php"

another example:

"website.com/templates/name2/index.php"

than it should include the file located here:

"website.com/content/templates/name2/content.php"

Also I want to overrun "Warning: include_once() [function.include-once]: http:// wrapper is disabled in the server configuration by allow_url_include=0" kind of error.. because is disabled and unsafe..

Is there a way to achieve this? Thank you!

like image 447
Adrian M. Avatar asked Apr 11 '10 17:04

Adrian M.


2 Answers

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.

like image 124
Sergey Kuznetsov Avatar answered Sep 17 '22 16:09

Sergey Kuznetsov


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" />
like image 38
vignesh Avatar answered Sep 19 '22 16:09

vignesh