【问题标题】:PHP get image from serverPHP从服务器获取图像
【发布时间】:2018-07-04 23:45:28
【问题描述】:

我正在尝试显示来自 PHP 服务器的图像。 这是我的功能:

function get_file($path) {
    $fileToGet = $GLOBALS['homedir'].$path;
    //echo $fileToGet.PHP_EOL;
    if (file_exists($fileToGet)) {
      //echo 'file exists';
      header('Content-Type: image/png');
      header('Content-Length: '.filesize($fileToGet));
      echo file_get_contents($file);
    }
}

我正在使用浏览器或邮递员,图像无效。

我错过了什么?

【问题讨论】:

    标签: php image apache server client


    【解决方案1】:

    我编辑了一点你的函数:

    function get_file( $path ){
        $fileToGet = $GLOBALS['homedir'];
        if( substr( $fileToGet, -1) != '/' ){
            // add trailing slash if needed
            $fileToGet .= '/';
        }
        $fileToGet .= $path;
    
        if (file_exists($fileToGet)) {
          header('Content-Type: image/png');
          header('Content-Length: '.filesize($fileToGet));
          echo file_get_contents($fileToGet);
        }
    }
    

    只是一个安全提示:如果$path 来自用户,则可能存在问题,因为他将能够访问其他文件。 想想这段代码:

    get_file( $_GET['path'] );
    

    那么用户就可以调用这个url了

    yoursite/yourpage.php?path=../../../mypreciousimage.png
    

    【讨论】:

    【解决方案2】:

    试试

    print file_get_contents($file);
    

    代替

    file_get_contents($file);
    

    【讨论】:

      【解决方案3】:

      你没有输出你正在阅读的文件的内容:

      file_get_contents($file);
      

      你需要回应它:

      echo file_get_contents($file);
      

      或者:

      readfile($file);
      

      您可能还希望将exit; 添加到该函数的末尾,以确保没有其他代码运行并且不会发送其他输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-23
        • 1970-01-01
        • 2011-10-27
        相关资源
        最近更新 更多