aozora
aozora

Reputation: 421

$_SERVER['DOCUMENT_ROOT'] creates extra slash at end

When I use $_SERVER['DOCUMENT_ROOT'] in my localhost it outputs: C:/apache2.2/htdocs.

However when I use it on my server it outputs: /var/www/

I can't use stripslashes() since it removes all slashes even from beginning. Any suggestion how to counter this? I don't mind if the outputs has slash or none at end. But I just want it to be the same for both files. So I don't keep changing paths by adding or removing slashes.

Btw I cannot change anything on my server. However I can change my local to match the server but don't know how.

Upvotes: 3

Views: 431

Answers (1)

Phil
Phil

Reputation: 164901

Try

rtrim($_SERVER['DOCUMENT_ROOT'], '/')

to normalise the string. See http://php.net/manual/function.rtrim.php.

I strongly recommend never relying on DOCUMENT_ROOT as it is an external dependency. Instead, use the magic constants __DIR__ and __FILE__ to refer to paths relative to your scripts. For example...

$someDirRelativeToThisFile = __DIR__ . '/some-dir'; // PHP >= 5.3.0
$someDirRelativeToThisFile = dirname(__FILE__) . '/some-dir'; // PHP < 5.3.0

See http://php.net/manual/language.constants.predefined.php

Upvotes: 2

Related Questions