PHP从服务器获取图像

时间:2018-01-25 16:32:44

标签: php image apache server client

我正在尝试从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);
    }
}

我使用的是浏览器或邮递员,图片无效。

我缺少什么?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

file_get_contents($file);

你需要回应它:

echo file_get_contents($file);

或者:

readfile($file);

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

答案 2 :(得分:0)

尝试

print file_get_contents($file);

而不是

file_get_contents($file);