如何通过一个独特的php文件下载多个图像


How to download multiple images through an unique php file?

我需要一个php文件,该文件能够从服务器上的文件夹下载多个图像,每个图像都有一个唯一的ID。

例如

我的服务器上有一个图像:/home/example/public_html/multipleimage/2.png

我想通过唯一的php文件下载该图像:http://example.com/file.php

我会键入以下网址:http://example.com/file.php?id=2浏览器必须返回图像。

但是。。。php文件应该如何?可以在不经过数据库的情况下完成吗?

谢谢。

<?php
header("Content-Type: image/png");
readfile(
    sprintf(
        '/home/example/public_html/multipleimage/%d.png', 
        $_GET['id']
    )
);

请参阅PHP手册中的以下条目:

  • header-发送原始HTTP标头
  • readfile-读取文件并将其写入输出缓冲区
  • sprintf-返回根据格式化字符串格式生成的字符串
  • $_GET-通过URL参数传递给当前脚本的变量的关联数组

请注意,我将sprintf%d一起使用,因此它将静默地将任何非数字id值转换为0,因此像../../etc/passwd这样的恶意输入将尝试读取0.png。如果你想使用除数字之外的任何其他东西,你需要对输入进行消毒,以防止目录遍历攻击和空字节中毒(在PHP 5.3.4之前):

  • filter_input-按名称获取特定的外部变量,并可选地对其进行筛选

我仍然不确定我知道你想要什么,但它来了:

<?php
if (array_key_exists('id', $_GET) && is_numeric($_GET['id'])) {
    header("Content-Type: image/png");
    echo file_get_contents("/home/example/public_html/multipleimage/".$_GET['id'].".png");
}
?>