AI摘要

本文旨在引导读者通过自主研究学习编写代码,以一个简单实例展开。通过新建 api.php 文件,利用PHP代码从 img.txt 文件中读取图片链接存入数组,随机选取链接,并根据 type 参数决定以JSON形式返回或直接跳转至图片链接。还提及若 img.txt 存于特定目录,需在 api.php 中修改路径。

此内容由AI生成,仅用于文章内容的总结

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

方法一、外链读取txt

新建文件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[array_rand($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"));
}

新建文件img.txt

http://example.com/image1.jpg
http://example.com/image2.jpg
http://example.com/image3.jpg


访问你的网址/api.php访问就可以实现了,api.phpimg.txt 理想存放目录是在同一目录下。
如果将img.txt放于特定目录。此时,需在api.php中修改$filename变量指定完整路径,如:
$filename = '/var/www/wwwroot/data/img.txt';

方法二、读取本地目录模式

<?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即可