dream_life5200 2014-07-14 08:59
浏览 32
已采纳

如何使用类插入图像(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

  • 写回答

1条回答 默认 最新

  • dousi4900 2014-07-14 09:04
    关注
    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">';
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!