Search code examples
phpapachexampphref

How can I use PHP to set my navbar hrefs to absolute paths?


I need to set these anchor href tags to absolute paths because when I have html docs in folders, the header where I include a lot of stuff doesn't work (need ../ in some cases).

I have looked at a few posts that have suggested using:

$root = realpath($_SERVER['DOCUMENT_ROOT']);

or

$root = "http://" . $_SERVER['SERVER_NAME'];

The first option resulted in an error:

localhost/:1 Not allowed to load local resource: file:///C:/xampp/htdocs/trips/index.php%7D

The second option resulted in this error:

Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in C:\xampp\htdocs\MountainPlanner\includes\header.php on line 17

Warning: include(http://localhost/MountainPlanner/includes/db.php): failed to open stream: no suitable wrapper could be found in C:\xampp\htdocs\MountainPlanner\includes\header.php on line 17

Warning: include(): Failed opening 'http://localhost/MountainPlanner/includes/db.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\MountainPlanner\includes\header.php on line 17

I am using XAMPP if that makes a difference.

Thank you!


Solution

  • HREF navbar path != System Path

    URL path

    It's what you see in your browser address, it's used by HTML (CSS, JavaScript, etc...). PHP don't need to worry about it (except by some streams functions).

    To create the base path dynamically, I've used this script

    httpProtocol = !isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' ? 'http' : 'https';
    
    $base = $httpProtocol.'://'.$_SERVER['HTTP_HOST'].'/';
    

    And, when put in the href a tag:

    <a href="<?php echo $base; ?>link" title="Link">Link</a>
    

    System Path

    It's what the server use to find any file on the server. PHP uses it to include/require any file located on the server or a shared one. Streams functions could use system path too and URL as well.

    As I can see, you're asking about system path. I've used this code to normalize the application path:

    ini_set('include_path',
        implode(
            PATH_SEPARATOR, 
            array_merge(
                array(dirname(__FILE__)),
                explode(PATH_SEPARATOR , ini_get('include_path'))
            ) 
        )
    );
    

    Then, my application root could be used as a absolute path only for my application:

    /Application/Require.php
    /Application/Script.php
    index.php
    

    It'll work on any file as well:

    require('Application/Require.php');
    require('Application/Script.php');