phphtmlheaderfootergeturl

Get url path to url links (PHP)


For get img url I use this on main sites

<a href="./index.html"><img src="./images/logo.png" class="" alt=""></a>

But for sub sites I need to use this

<a href="../index.html"><img src="../images/logo.png" class="" alt=""></a>

How I can get url site using PHP code for this because I would like to create two PHP files, header and footer and I need something like get url site for url links and should work on both sites (main and sub).

I was trying to use

<img src="<?php echo url('images/logo.png') ?>" alt="">

but image not show.

Thanks


Solution

  • If your domain is www.example.com you might want to try getting the required information from the REQUEST_URI that is $_SERVER['REQUEST_URI']

    For example:

    function get_image_path($image) {
    
        $parts = explode('/',$_SERVER['REQUEST_URI']);
        $temp = array_shift($parts);
        $image_path = '';
        foreach($parts as $part){
            $image_path.='../';
        }
        return $image_path.$image;
    }
    

    Usage:

    print get_image_path('images/1.jpg');
    

    This should work for www.example.com/script.php and www.example.com/sub/script.php (and for any number of subfolders nested or not)

    Use the same logic for your url($file) function