Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP include file in webroot from file outside webroot

Tags:

include

php

I have a php file outside my webroot in which I want to include a file that is inside the webroot.

folder outside webroot
- > php file in which I want to include
webroot
- > file to include

So I have to go one directory up, but this doesnt work:

include('../webroot/file-to-include.php');

Include full path doesn't work either:

include('home/xx/xx/domains/mydomain/webroot/file-to-include.php');

How can I accomplish this?

like image 852
user1662927 Avatar asked Nov 25 '12 11:11

user1662927


2 Answers

Full path should be:

include('/home/xx/xx/domains/mydomain/webroot/file-to-include.php');

Or you should set the path like:

include(__DIR__ . '/../webroot/file-to-include.php');  // php version >= 5.3
include(dirname(__FILE__) . '/../webroot/file-to-include.php');  // php version < 5.3
like image 143
xdazz Avatar answered Oct 03 '22 23:10

xdazz


Have this in a common file, shared by all your php sources outside the webroot:

<?php

  define('PATH_TO_WEBROOT', '/home/xx/xx/domains/mydomain/webroot');

And then use the following to include files.

<?php
  include (PATH_TO_WEBROOT.'/file-to-include.php');

If the location of your webroot changes, you will only have to change that once in your code base.

You can configure php to automatically prepend a given file to all your scripts, by setting the auto_prepend_file directive. That file could for instance contain the PATH_TO_WEBROOT constant, or require_once the file which contains it. This setting can be done on a per domain or per host basis (see the ini sections documentation).

Also, consider using the autoload feature if you are using classes extensively.

like image 39
didierc Avatar answered Oct 03 '22 22:10

didierc