gpt4 book ai didi

php - 使 src 指向一个 php 页面

转载 作者:行者123 更新时间:2023-11-29 00:12:45 25 4
gpt4 key购买 nike

我将所有图片保存在普通用户无法访问的根目录中。我随机生成所有文件名,所以我不想让他们知道文件的路径或名称。目前,我有这样的 img 元素:

<img src="get_image.php?id=1">

我的 get_image.php 页面是这样的:

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';

$uploaddir = '/root/......./uploads/'; //Direct path from root to folder holding files
$id = $_GET['id'];

if(!is_numeric($id)) {
die("File id must be numeric");
}

// A QUICK QUERY ON A FAKE USER TABLE
$stmt = $mysqli->prepare("SELECT `name`, `mime` FROM `uploads` WHERE `filmId`=?");
$stmt->bind_param("i", $id);
$stmt->execute();

$stmt->bind_result($name, $mime);

// GOING THROUGH THE DATA
while($stmt->fetch()) {

header("Content-Type: " . $mime);
readfile($uploaddir.$name);
}

?>

如果有办法我可以做到这一点?我不想像这样直接调用图片文件src:

<img src="../../../uploads/file.jpg"> <!-- I don't want to do this -->

这样做会给用户(或攻击者)提示我将上传的文件保存在哪里。这些图像是用户上传的,因此如果攻击者上传带有恶意代码的图像(即使我有很多代码检查和验证文件),他们也不知道该文件的保存位置。

另外,我不熟悉网络开发并确保其安全。如果您有任何提示或指示可以添加到我必须让我的网页更安全的东西上,请随时。谢谢!

我正在使用 this link确保此功能安全。

解决方案:

代替:

    header("Content-Type: " . $mime);
readfile($uploaddir.$name);

我把这个:

    header("Content-Type: " . $mime);
$contents = file_get_contents($uploaddir . $name);
echo $contents;

而且有效。

最佳答案

不仅如此,您可以做到这一点。你甚至可以点一个 <img>到似乎是图像路径的 PHP 脚本。例如:

<img src="phpimages/my_image.png" />

这个技巧需要一个 Apache HTTP 服务器(您无疑会使用它)和 mod_rewrite它的插件(你肯定已经安装了)。你可以把 .htaccess文件在 /phpimages/内容如下:

RewriteRule ^([^\.]+)\.(png|jpg|gif)$   /image.php?file=$1.png [NC,L]

如果您只需要用户 ID,可以将正则表达式限制为:

RewriteRule ^([0-9]+)\.(png|jpg|gif)$   /image.php?file=$1.png [NC,L]

这个过程进一步解释here .

在脚本中 image.php (在同一目录中),然后您将文件名作为字符串获取,例如:

$filename = $_GET["file"];  //eg.: "file1.jpg"

不要忘记过滤掉 ../ 破解尝试。要将文件打印给用户,前提是它确实存在,请使用 readfile :

const REAL_AVATAR_PATH = "../../../uploads/"
if(file_exists(REAL_AVATAR_PATH.$username)) {
header("Content-Type: image/jpg"); //For simplicity, I have ommited to send different header for different images as "png", "gif" and so on.
readfile(REAL_AVATAR_PATH.$username);
}
else {
header("HTTP/1.0 404 Not Found");
die("Error 404 - sorry");
}

在您的情况下,您可以将路径设置为 /avatars/[number].png (并将所有图像转换为 png )。

关于php - 使 <img> src 指向一个 php 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com