Lovelock
Lovelock

Reputation: 8085

Relative URLS across different sub folders

Looking for a way of allowing my links and include URLs etc to work on my local machine correctly as well as on my live site.

I have for example a common.php file which contains my DB connection.

I also have a init.php file which is included on every page and inside that includes the common.php file (among others)

For now, i have used

include './common.php';

However, if i am in a page e.g. web/settings

the ./ points to the settings folder.

What should i be using as a relative URL that will work across the whole site no matter what folder etc?

Upvotes: 0

Views: 1346

Answers (3)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

the quick answer for a path is this.

__DIR__ = current working directory so If you have MVC type architecture ( single point of entry aka front controller, basically everything starts off in one file, typically index.php, and the rest are included ) you can just define a constant like this in that main file.

define( 'BASE_PATH', __DIR__.'/' );

So if you have like this

root
    index.php //define basepath
    includes :
        other.php
    template :
        temp.php

in other you can just do

include BASE_PATH . 'template/temp.php';

everything will be tied by that one base set in the main index.php file, and as long as the folder i put above as root contains everything you can move that where ever you want because of the dynamic part __DIR__

The long answer is to use a PSR-0 autoloader but that might be a bit overkill.

As a side not if you are on PHP < 5.3 use this instead of __DIR__

dirname(__FILE__)

Upvotes: 0

Chris Magnussen
Chris Magnussen

Reputation: 1527

You could use $_SERVER['DOCUMENT_ROOT'] for this.

set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );

// Now, you can specify your path relative to your DOCUMENT_ROOT.
include('common.php'); // Assuming your common.php file is in your root path.

You'll find it alot more convenient using namespaces though, so you might want to go down that road.

Upvotes: 0

Max
Max

Reputation: 887

How about /? It refers to the base, and from there you can use the absolute path:

include "/absolute/path/to/file/common.php";

A relative URL is always affected by the current directory, and you can't make it the same no matter where you are on the site. You need to use absolute paths.

Upvotes: 1

Related Questions