且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PHP显示来自外部Web根文件夹的所有图像

更新时间:2023-09-25 15:27:22

问题是您没有解析QueryString变量您传递给call_images.php,但改为运行相同的数据库查询,该查询只会返回数据库每次返回的第一张图像。这是一个(希望)正确的版本。

The problem is you're not parsing the QueryString variable you pass to call_images.php, but instead running the same database query, which will just return the first image that the database comes back with every time. Here is a (hopefully) corrected version.

<?php
// Get our database connector
require("includes/copta.php");

$imgLocation = '/ uploadz/';

$fn = mysql_real_escape_string($_GET['imgPath']);

$sql = "select filename from people WHERE filename = '{$fn}'";

$result = mysql_query($sql) or 
    die ("Could not access DB: " . mysql_error());   

if (mysql_num_rows($result) == 0) {
    header('HTTP/1.0 404 Not Found');
    die('The file does not exist');
}
$imgName = mysql_result($result, 0, 0); 
$imgPath = $imgLocation . $imgName;

// Make sure the file exists
if(!file_exists($imgPath) || !is_file($imgPath)) {
    header('HTTP/1.0 404 Not Found');
    die('The file does not exist');
}

// Make sure the file is an image
$imgData = getimagesize($imgPath);
if(!$imgData) {
    header('HTTP/1.0 403 Forbidden');
    die('The file you requested is not an image.');
}


// Set the appropriate content-type
// and provide the content-length.

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header("Content-Type: image/jpg");
header("Content-length: " . filesize($imgPath));

// Print the image data
readfile($imgPath);
exit();
?>

关于这些更改的认识:


  • $ fn = mysql_real_escape_string($ _ GET ['imgPath']); 获取通过查询字符串传递的变量,然后对其进行转义,以便我们再次通过数据库运行它。通过这种方式,我们可以确保用户没有使用相对路径来尝试公开他们不应该访问的图像(除非您拥有它的数据库记录;安全是由它来实现的)。

  • 我完全删除了循环,没有必要

  • 我使用了 mysql_result() ,因为我们只需要一个字段的数据即可。

  • 我建议切换 readfile()用于 fpassthru() ,它需要调用fopen,但不会在内存中缓冲文件的内容。

  • $fn = mysql_real_escape_string($_GET['imgPath']); gets the variable you passed via querystring, and then escapes it so we can run it through the database again. This way we can be sure that the user hasn't used relative paths to try to expose an image that they shouldn't have access to (unless you have a database record for it; security is what you make it).
  • I removed the loop entirely, it was not necessary
  • I used mysql_result() since we only needed one field's worth of data.
  • I would recommend switching readfile() for fpassthru(), which requires a call to fopen, but does not buffer the contents of the file in memory.