2

Possible Duplicate:
relative path in require_once doesn’t work

I have a project structure as such:

ProjectName/
   src
     test
       TestClass.php
   tests
     TestTestClass.php

WhenI try and do require_once '/ProjectName/src/test/TestClass.php'; into tests/TestTestClass.php I get an error from PHP stating that: no such file or directory.

I have checked the spelling, I have checked everything. I cannot give it the full /home/userName/bla/bla path as I need to hand this off to some one else.

Any ideas?

Community
  • 1
  • 1
Adam
  • 37
  • 1
  • 6

4 Answers4

2

This is expected behaviour. When you execute TestTestClass.php, your working directory is set to ProjectName/tests.

It would be better to use ../src/test/TestClass.php.

Your path is actually absolute, so you will be working straight from /, which is not what you're expecting. If your include_path is set to your server's directory root, then your code will work without the first /. If you don't wish to rely on include_path or arbitrary levelling (with ..), you can always set an environment variable in your first file that defines the full path to your application root, then use that for all includes.

For example, /ProjectName/index.php:

define('APPPATH', __DIR__);

.. and in /ProjectName/tests/TestTestClass.php:

require_once APPPATH . '/src/test/TestClass.php';
Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
1

absolute filepaths passed to require/include/require_once/include_once all work from the filesystem root, not to the webserver root

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

Use the special DIR to get the current path of the script and like so it will be easier for you to find script paths:

require_once(__DIR__ . '../folder/whatever.php');
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
0

You'd benefit from creating a path constant for your project. This is quiet easy to do with the __FILE__ constant and dirname().

define('ROOT_PATH', dirname(__FILE__));

The above could be put in a configuration file so it is easier to include files throughout your project.

require_once ROOT_PATH . '/src/test/TestClass.php';

I'd also suggest looking into an autoloader.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174