如何使用类插入图像(dirname和filepath问题)

I have a method in a class I would like to use in order to show an image in a page that could be placed in any directory.

Basically, the class file would be at the root directory and the class would look like this:

class A{
    function showImage(){
        echo '<img src="img/file.jpg">';
    }
}

Problems occur when I call the method in a page which is in a subdirectory. For example, if I use showImage() in 'subdir/mypage.php', then the image link is broken.

I have looked into $_SERVER['HTTP_HOST'] and dirname(__FILE__) but I coud not find the right mix to get the right image path that could be used in order to show the image from any directory.

What function should I used in the class to get the file path dynamically that would depending on the directory where I am calling showImage()?

Many thanks

class A{
    function showImage($link){
        $link = str_replace('/home/public', '', $link);
        echo '<img src="' . $link . '">';
    }
}

and use it like this:

$a->showImage(getcwd().'/img/file.jpg');

The getcwd() will get the directory, then remove the first absolute path to your public folder in the function.

Example case:

  • test.php is placed in /home/public/images/{test.php}
  • class.php is placed in /home/public/{class.php}

test.php does:

$a->showImage(getcwd().'/img/file.jpg');

What it'll send to class.php is:

$a->showImage('/home/public/images/img/file.jpg');

Then in your function it'll remove /home/public and show this link:

<img src="/images/img/file.jpg">

MY BAD

I didn't read the answer right. Here's the solution you're looking for:

class A{
    function showImage(){
        $root = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
        echo '<img src="' . $root . 'img/file.jpg">';
    }
}