How to get DOCUMENT_ROOT to work on both localhost and web host?
Asked Answered
E

2

2

I have a WordPress plugin that I would like to work on localhost as well as in deployment without modification, but I can't seem to set the location for a directory using one statement.

I would like to do this:

$feed->set_cache_location($_SERVER['DOCUMENT_ROOT'] . '/wp-content/cache');

While that works on the web host. On localhost it produces this error:

C:/xampp/htdocs/wp-content/cache/a547b8792c3144c98549be23ef1465e7.spc is not writeable

On localhost, I need to set it to this to get it work:

$feed->set_cache_location($_SERVER['DOCUMENT_ROOT'] . '/mysite/wp-content/cache');

Surely there must be something that works both on localhost and on a web host!

Thanks.

Evanevander answered 13/6, 2009 at 6:37 Comment(0)
B
2

Check this out Determining Plugin and Content Directories WP already has this.

Bring answered 13/6, 2009 at 6:51 Comment(0)
M
4

So it looks like the OP would be interested in either the WP_CONTENT_DIR or WP_PLUGIN_DIR predefined constants.

This is for Wordpress installs. But for non-WP situations, I've found the following snippet to be useful:

$docroot = realpath((getenv('DOCUMENT_ROOT') && ereg('^'.preg_quote(realpath(getenv('DOCUMENT_ROOT'))), realpath(__FILE__))) ? getenv('DOCUMENT_ROOT') : str_replace(dirname(@$_SERVER['PHP_SELF']), '', str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__))));

This is in similar situations where I've wanted things to work on both a localhost/dev environment and a server environment, where the docroot locations differed. BUT even more important is that this works in the situations where I need to run a PHP file standalone.

UPDATE

The code above has been edited February 2022 to improve and remove deprecated and removed functions such as ereg:

$docroot = realpath((getenv('DOCUMENT_ROOT') && 
preg_match('^'.preg_quote(realpath(getenv('DOCUMENT_ROOT')),'/').'^', 
realpath(__FILE__))) ? getenv('DOCUMENT_ROOT') : 
str_replace(dirname(@$_SERVER['PHP_SELF']), '', 
str_replace(DIRECTORY_SEPARATOR, '/', __DIR__)));
Malda answered 20/5, 2011 at 16:50 Comment(1)
This did not work for me - returned path including filename. I ended using this form which gets root which is one folder higher than my current file: if (!$_SERVER['DOCUMENT_ROOT']) $_SERVER['DOCUMENT_ROOT'] = realpath(dirname(FILE).'/../');Soldierly
B
2

Check this out Determining Plugin and Content Directories WP already has this.

Bring answered 13/6, 2009 at 6:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.