Perocat
Perocat

Reputation: 1521

Define a constant and use it on all pages

I use index.php as routing page.

I'd like to:

define('ROOT_DIR', __DIR__);

on index.php and use ROOT_DIR in all pages, is it possible without including nothing else?

Or is this the only way?

1) Create a file globals.php on the DOCUMENT_ROOT directory

2) define('ROOT_DIR', __DIR__); in globals.php

3) Include globals.php in every page of the site to use ROOT_DIR:

include $_SERVER['DOCUMENT_ROOT'].'/globals.php';

Which are the advantages using a constant?

Isn't it simplier to use always __DIR__?

Can you please tell me which is definitively the best and most usefull method to manage path when including files, etc. on php?

Thank you!

EDIT - FINAL SOLUTION?

1) Create a file globals.php e.g. on /WEB/mysite/htdocs/includes/

2) On globals.php define a constant with: define('ROOT_DIR', __DIR__);

3) On every file of the site include 'globals.php';. Eg. if I want to include globals.php on /WEB/mysite/htdocs/test/header.php I'll use include '../includes/globals.php

4) On every include on every file use include ROOT_DIR.'/path_to_file_relative_to_ROOT_DIR/file.php'

5) E.g. to include /WEB/mysite/htdocs/scripts/script1.php on /WEB/mysite/htdocs/test/header.php I'll write:

include '../includes/globals.php';
include ROOT_DIR.'/../scripts/script1.php';

And never change the path of globals.php;

EDIT2 USING INDEX AS ROUTING PAGE

.htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

index.php used as routing page:

<?php
include 'globals.php';

$uri = $_SERVER["REQUEST_URI"];
$trimmeduri = trim($uri, '/');

if($uri == '/'){
    $sigle = $link->query("SELECT sigla AS lingue FROM LINGUE");

    while($lingue_db = mysqli_fetch_array($sigle)){
        $lingue[] = $lingue_db['lingue'];
    }

    $client_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

    if(in_array($client_lang, $lingue)){
        header("location: http://www.mysite.com/$client_lang/index.php");
    }else{
        header("location: http://www.mysite.com/it/index.php");
    }

}else{
    include "sql.php";
    $link = new mysqli($host, $user, $pw, $db);
    $link->set_charset('UTF8');
    $trimmeduri = $link->real_escape_string($trimmeduri);
    $urlliste = $link->query("SELECT Nome FROM LISTE WHERE URL = '$trimmeduri'");
    while($urllista = mysqli_fetch_array($urlliste)){
        $lista = $urllista['Nome'];
    }
    $uri_count = mysqli_num_rows($urlliste);
    $urlliste->close();

    if($uri_count == '1'){
        header("location: http://www.mysite.com/pages/page.php?name=$lista");
    }elseif($uri_count > '1'){
        header('HTTP/1.0 400 Bad Request', true, 400);
        require_once "errors/400badrequest.html";
    }else{
        header("HTTP/1.0 404 Not Found");
        require_once "errors/404notfound.php";
    }
}
?>

The problem is that the constant defined on globals.php is not avaiable on the other pages... Why?

Upvotes: 2

Views: 4359

Answers (1)

Niels Keurentjes
Niels Keurentjes

Reputation: 41968

If you want code to be executed on every page, you have to make sure it's executed on every page. Easiest way to ensure that is to put it in a central file that's included from every page, that's what the include statement is for.

As for some of the big advantages of using constants:

  1. You only have to change it one time if it changes, and all the thousands of references automatically take the new value.
  2. Constants keep your code readable and devoid of 'magic numbers' etc. - it's easier to read code that references MAXIMUM_SUPPORTED_LENGTH than an arbitrary comparison with a number.
  3. Constants can contain precalculated constants.

For the third: in your own sample, dirname(__FILE__) would actually result in a different value depending on the folder in which the invoking PHP script is located. Putting it into a constant eliminates that issue. Secondly, calling dirname(__FILE__) will actually internally:

  1. Look up which file we are executed
  2. Look up the dirname function and invoke it
  3. Do some nasty string processing to determine the directory name

It's not terribly slow, but calling it 500 times is. And if the result is going to be the same 500 times anyway, why not do it once and store it in a constant for later reference? Makes the web page load faster in the end.

Finally - a completely offtopic remark, but relevant to your specific question - as of PHP 5.3.0 there is also a __DIR__ constant which is literally defined to be identical to dirname(__FILE__). Read more about it here.

Upvotes: 3

Related Questions