Search code examples
phpdocument-root

PHP - Smarter Files Referencing


I have some simple PHP scripts that helps me with small tasks on each of my servers. I run it via the CLI only, since not all my servers have Apache, but I install PHP on all. I'd like to make it portable, at any time.

Here's my scripting scheme:

dir_libs/top.php  (top.php references all my classes and functions)
dir_logs/  (holds logs I may create)
runstats.php  (this is what I initialize from CL)

Here's what I have done on one of my servers:

runstats.php

<?php
require('/home/myuser/public_html/dir_libs/top.php'); // holds functions
require('/home/myuser/public_html/dir_logs/'); // holds logs from my functions

 echo display_stats();
 echo "\n---------------------\n";
?>

I obviously need to change the absolute paths, depending on the server, since I don't always keep things the same - even if I clone a virtual machine.

I tried $_SERVER['DOCUMENT_ROOT'], but that appears to need a browser to know where it lies.

Does anyone have a suggestion?
Again, I only intend to run the runstats.php from the command-line.


Solution

  • This is normally done in PHP using the __DIR__ magic constant, like this:

    require_once(__DIR__ . '/path/to/file.php');
    

    To get to your top-level from a different embedded directory, you can do something like this::

    require_once(__DIR__ . '/../dir_libs/top.php');
    

    For versions of PHP previous to 5.3.0, you can use dirname(__FILE__) in place of __DIR__.

    For a real-world example, you can look at the Laravel project, which uses a few different tricks in the .php files found in the public and bootstrap directories to reference other files in the project:

    https://github.com/laravel/laravel/tree/v4.1.18

    (I've linked to the current version, in case it changes later on.)