我在网上找到了一些代码来访问我的数据库,以检索带有 mime 扩展名的存储文件,并将该信息读取到我存储实际图像的目录中。 代码源链接
<div id="display-image">
<?php
$query = " select * from image ";
$result = mysqli_query($db, $query);
while ($data = mysqli_fetch_assoc($result)) {
?>
<img src="./image/<?php echo $data['filename']; ?>">
<?php
}
?>
</div>
在访问数据库的每个实例中,我喜欢使用 die 或 exit(0)。但是,当我尝试将其与此代码一起使用时,页面无法正确加载。这是我的编码方式:
<?php
// This page uploads to profile pic into the profile page
include("database_connection.php");
$user = $_SESSION['active_user']['username'];
$get_img = "SELECT * FROM test WHERE User='$user' LIMIT 1";
$runit = mysqli_query($db,$get_img);
while($pic = mysqli_fetch_assoc($runit))
{
?>
<img src="img/<?php echo $pic['image_file01']; ?>" >
<?php
exit(0);
}
?>
所以上面的代码位于一个单独的文件中,我将其包含在我的个人资料页面上,如下所示:
<div class="body-align-left">
<br><br>
<!-- Profile Image-->
<?php
include('upload.php');
?>
</div>
虽然代码看起来工作正常,但我不太确定使用 while 语句是解决此问题的黄金方法。此外,我想知道这段代码实际上有多安全。什么是更好的方法?就像我上面说的,如果我尝试使用 exit(0) 或在代码块内死亡,它不会完全加载页面。
首先,您当前的代码很容易发生
SQL
注入,因为您直接将 username
输入嵌入到 SQL
查询中。这可以被利用来运行恶意的 SQL
语句。为了解决这个问题,您需要始终准备好您的查询。
示例:如何准备查询。
?
用作占位符,我们稍后将值绑定为字符串s
。这样,查询就会按照您想要的方式处理,并且用户输入无法操作它。
$stmt = $db->prepare("SELECT image_file01 FROM test WHERE User=? LIMIT 1");
$stmt->bind_param("s", $user);
其次,您不需要在 while 循环中使用
exit
,因为您已将查询限制为仅一个结果 ... LIMIT 1
。在这里,if 语句更合适,因为我们返回一张图像或不返回任何内容。
// First execute the prepared query
if ($stmt->execute()) {
// Get the results:
$result = $stmt->get_result();
// If profile image is found, echo the img
if ($row = $result->fetch_assoc()) {
echo '<img src="img/' . $row['image_file01'] . '" >';
}
// No images were found. Here, you do whatever you want.
// For example, display a default profile image.
// If you want nothing to happen, you can remove this
// else statement completely.
else {
echo "No image found.";
}
}
// Prepared query failed
else {
echo "Database error: " . $stmt->error;
}