admin 发表于 2025-7-30 09:03:51

两种方式轻松自制随机图片获取API

在互联网中,我们常常需要快速获取各类图片资源。今天,就为大家带来一个超实用的教程,教你轻松搭建属于自己的随机图片获取API,从此告别四处寻觅图片API的繁琐。

方法一、外链读取txt
1.新建文件api.php
    <?php
    // 使用__DIR__常量获取当前脚本所在目录,并拼接文件路径
    $filename = __DIR__. '/img.txt';
    if (!file_exists($filename)) {
      die('文件不存在');
    }
    // 打开文件并检查是否成功
    $fs = fopen($filename, "r");
    if (!$fs) {
      die('无法打开文件');
    }
    // 从文本获取链接
    $pics = [];
    while (!feof($fs)) {
      $line = trim(fgets($fs));
      if ($line!== '') {
            array_push($pics, $line);
      }
    }
    fclose($fs);
    // 从数组随机获取链接
    $pic = $pics;
    // 获取type参数
    $type = isset($_GET['type'])? $_GET['type'] : '';
    switch ($type) {
      // JSON返回
      case 'json':
            header('Content - type:text/json');
            die(json_encode(['pic' => $pic]));
      default:
            // 验证链接是否合法
            if (!filter_var($pic, FILTER_VALIDATE_URL)) {
                die('无效的图片链接');
            }
            die(header("Location: $pic"));
    }2.新建文件img.txt
http://example.com/image1.jpg
    http://example.com/image2.jpg
    http://example.com/image3.jpg

方法二、读取本地目录模式
<?php
    $img_array = glob("images/*.{gif,jpg,png}", GLOB_BRACE);
    if (!empty($img_array)) {
      $img = array_rand($img_array);
      $dz = $img_array[$img];
      header("Location: " . $dz);
      exit; // 重定向后终止脚本执行
    } else {
      echo "没有找到符合条件的图片文件。";
    }
    ?>图片丢到images文件夹下,访问api.php即可
来源:白衣博客
页: [1]
查看完整版本: 两种方式轻松自制随机图片获取API