rattanak
rattanak

Reputation: 1508

PHP, include absolute path from home directory

In html, the backslash(/) at the beginning tells the system to start looking from the home directory. For example,

<a href="/folder1/example.css">Link</a>
<img scr="/images/example.jpg">Image />

To repeat, the / tells the system to look from the home directory.

Is there a way to do same thing in PHP as in?

<?php include '/header.php'; ?>

The php code below will only look up header.php one directory below the current directory. Please comment if my question is not clear enough. Thanks.

Upvotes: 1

Views: 5510

Answers (2)

gargantuan
gargantuan

Reputation: 8944

If you mean "home" as in the web root, then $_SERVER["DOCUMENT_ROOT"] should do the trick.

As pointed out elsewhere, that may not return what you expect. The code below should still work though.

A lot of people define an ABSPATH constant. If your app is always routed through index.php, then the following might be easier to implement at the top of index.php

define( 'ABSPATH', dirname(__FILE__) . '/' );

// this can then be called from any where
require_once(ABSPATH . "includes/header.php");

// or in your example
<img src="<?php echo ABSPATH; ?>images/example.jpg" />

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

$_SERVER['DOCUMENT_ROOT'] quite probably refers to the directory you are trying to access.

Upvotes: 4

Related Questions