Php – How does filepaths in php work

filepathPHP

The problem is that I use the method file _ get _ contents("body.html") in a class that is in the same folder as body.html. The problem is that I get an error saying that the file could not be found. This is because I from another class require the file that uses the method file _ get _ contents("body.html"), and suddenly I have to use "../body/body.html" as filepath..!

Isn't that a bit strange? The class that calls the method file _ get _ contents("body.html") is in the same folder as body.html, but because the class is required from another class somewhere else, I need a new filepath?!

Here's a short list over directories and files:

lib/main/main.php
lib/body/body.php
lib/body/body.html

This is body.php:

class Body {

 public function getOutput(){
  return file_get_contents("body.html");
 }
}

This is main.php:

require '../body/body.php';

class Main {

 private $title;
 private $body;

 function __construct() {

  $this->body = new Body();
 }

 public function setTitle($title) {
  $this->title = $title;
 }

 public function getOutput(){
  //prints html with the body and other stuff.. 
 }
}

$class = new Main();
$class->setTitle("Tittel");
echo $class->getOutput();

The thing I ask for is a fix on the error that body.php is in the same folder as body.html but I have to change the path when a another class requires body.php from somewhere else in the method file _ get _ contents("body.html")

Thanks!

Best Answer

The scope of PHP's file-based functions always starts at the point of the first file in the execution stack.

If index.php is requested, and includes classes/Foo.php which in turn needs to include 'body/body.php', the file scope will be that of index.php.

Essentially, the current working directory.

You have some options, though. If you want to include/open a file in the same directory as the current file, you can do something like this

file_get_contents( dirname( __FILE__ ) . '/body.html' );

Or, you can define a base directory in a constant and use that for your inclusion

define( 'APP_ROOT', '/path/to/app/root/' );
file_get_contents( APP_ROOT . 'lib/body/body.html' );