-1

I am using WAMP (Apache2) and I have a PHP command which goes like:

$file='/path/to/file.txt';

After some testing and diagnosis through the command realpath, I found out that the file is being grabbed from F:/path/to/file.txt rather than F:/wamp/www/path/to/file.txt. After searching through StackOverflow, people said to check the DocumentRoot inside of the httpd.conf. I did this and the DocumentRoot is /wamp/www (like it should be).

Any ideas? I really don't want to redo this code if I don't have to.

Thanks!

CodeGodie
  • 12,116
  • 6
  • 37
  • 66
Amath1an
  • 23
  • 1
  • 7

2 Answers2

2

Use the PHP system vars http://php.net/manual/en/reserved.variables.server.php

$file = $_SERVER['DOCUMENT_ROOT'] . '/path/to/file.txt';
David Soussan
  • 2,698
  • 1
  • 16
  • 19
  • If anyone reads this question from a similar question, this method also works (tried it out). I decided to go with Thomas's answer because it seems less 'hacky' to define a document root. Thank you though David, I will definitely keep this in mind. – Amath1an Aug 17 '15 at 13:29
  • The thing with Thomas's answer is that you have defined a global constant within a file whose actual location may not be in the root dir. It also means that if the application is refactored and that file moved then the path will be wrong. $_SERVER['DOCUMENT_ROOT'] on the other hand is already defined and will only change if the server's configuration file is changed, which would be the behaviour you want anyway. Code it once use it many. It will also be correct for every server when you move from dev to test and production. This is actually the 'best practice' for these reasons. – David Soussan Aug 18 '15 at 15:04
1

What you could do is set a constant to the root path of the index.php location:

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

Then you can access the file from this path:

$file = ROOT_PATH .'/path/to/file.txt';
Thomas
  • 364
  • 2
  • 9
  • This seemed to work! Just out of curiosity, is considered a best practice or just a "How to fix it easily"? – Amath1an Aug 17 '15 at 13:22
  • I have seen this in a lot of projects. I think it is always best to know from which point you try to access files. There are a number of approaches you could use. This one I find the easiest. – Thomas Aug 17 '15 at 13:26
  • Great, I will go with this. Thanks a lot! – Amath1an Aug 17 '15 at 13:27