每日必应壁纸API

这段 PHP 代码的目的是从 Bing 的每日壁纸 API 获取壁纸信息,并根据请求的类型返回壁纸数据或 JSON 格式的壁纸信息。以下是对代码的详细解释和部署后的调用示例。

具体代码如下:

<?php

function getBingWallpaper() {
    // 构建 Bing 每日壁纸 API 的 URL
    $url = 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1';

    // 使用 cURL 发起 HTTP 请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);

    // 检查是否请求成功
    if ($response === false) {
        return false;
    }

    // 解析 JSON 响应
    $data = json_decode($response, true);

    // 检查是否解析成功
    if (!is_array($data) || empty($data['images'])) {
        return false;
    }

    // 提取壁纸相关信息
    $image = $data['images'][0];
    $imageUrl = 'https://www.bing.com' . $image['url'];
    $title = $image['title'];
    $copyright;

    // 构建返回数据
    $result = [
        'imageUrl' => $imageUrl,
        'title' => $title,
    ];

    return $result;
}

// 检查传入的参数,确定返回类型
$type = isset($_GET['type']) ? $_GET['type'] : 'json';

// 调用函数获取壁纸信息
$bingWallpaper = getBingWallpaper();

// 检查是否成功获取壁纸信息
if ($bingWallpaper !== false) {
    // 根据类型返回数据
    if ($type === 'image') {
        // 直接返回图片
        header('Content-Type: image/jpeg');
        readfile($bingWallpaper['imageUrl']);
    } else {
        // 返回 JSON 格式的壁纸信息
        header('Content-Type: application/json');
        echo json_encode($bingWallpaper);
    }
} else {
    // 返回错误信息
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(['error' => 'Failed to fetch Bing wallpaper.']);
}
?>

AI生成的代码解析

  1. 定义 getBingWallpaper 函数:

    function getBingWallpaper() {
        // 构建 Bing 每日壁纸 API 的 URL
        $url = 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1';
    • 该函数通过构建 API 的 URL 来请求 Bing 每日壁纸数据。
    • idx=0 表示获取今天的壁纸,n=1 表示只获取一张壁纸。
  2. 发起 HTTP 请求:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    • 使用 cURL 初始化请求,设置请求的 URL 和返回数据的方式(CURLOPT_RETURNTRANSFER 设置为 true,意味着返回数据会作为字符串输出,而不是直接输出到浏览器)。
    • 执行请求并将响应保存到 $response 变量。
  3. 检查请求结果:

    if ($response === false) {
        return false;
    }
    • 如果请求失败,函数返回 false
  4. 解析 JSON 响应:

    $data = json_decode($response, true);
    if (!is_array($data) || empty($data['images'])) {
        return false;
    }
    • 解析 JSON 响应并检查数据格式是否正确。
    • 如果解析失败或响应数据中没有 images 键,则返回 false
  5. 提取壁纸信息:

    $image = $data['images'][0];
    $imageUrl = 'https://www.bing.com' . $image['url'];
    $title = $image['title'];
    $result = [
        'imageUrl' => $imageUrl,
        'title' => $title,
    ];
    • 提取壁纸的 URL 和标题。
    • 构建包含壁纸信息的数组 $result
  6. 处理请求类型并返回结果:

    $type = isset($_GET['type']) ? $_GET['type'] : 'json';
    $bingWallpaper = getBingWallpaper();
    if ($bingWallpaper !== false) {
        if ($type === 'image') {
            header('Content-Type: image/jpeg');
            readfile($bingWallpaper['imageUrl']);
        } else {
            header('Content-Type: application/json');
            echo json_encode($bingWallpaper);
        }
    } else {
        header('HTTP/1.1 500 Internal Server Error');
        echo json_encode(['error' => 'Failed to fetch Bing wallpaper.']);
    }
    • 根据 type 参数决定返回的内容类型:imagejson
    • 如果 typeimage,设置响应的 Content-Typeimage/jpeg 并直接读取并输出壁纸图片。
    • 如果 type 为其他值或未设置,返回 JSON 格式的壁纸信息。
    • 如果无法获取壁纸数据,返回 HTTP 500 错误和错误信息。

获取用户IP地址

具体代码如下:

<?php
header("Content-Type: application/json");

function getRealIpAddr() {
    $ip = '';

    // 检查是否存在 HTTP_CLIENT_IP
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    // 检查是否存在 HTTP_X_FORWARDED_FOR,并处理代理 IP 地址列表
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim(end($ipList));
    }
    // 获取 REMOTE_ADDR 作为备选方案
    elseif (!empty($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    // 对 IP 地址进行验证
    if (filter_var($ip, FILTER_VALIDATE_IP)) {
        return $ip;
    } else {
        return 'Unable to determine IP address';
    }
}

// 获取用户真实 IP 地址
$user_ip = getRealIpAddr();

// 返回 JSON 格式的 IP 地址
$response = array(
    'ip' => $user_ip
);

echo json_encode($response);
?>

AI生成的代码详解

  1. 设置响应头:

    header("Content-Type: application/json");
    • 设置响应内容的 MIME 类型为 application/json,表明返回的数据格式是 JSON。
  2. 定义 getRealIpAddr 函数:

    function getRealIpAddr() {
        $ip = '';
    
        // 检查是否存在 HTTP_CLIENT_IP
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
        // 检查是否存在 HTTP_X_FORWARDED_FOR,并处理代理 IP 地址列表
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim(end($ipList));
        }
        // 获取 REMOTE_ADDR 作为备选方案
        elseif (!empty($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    
        // 对 IP 地址进行验证
        if (filter_var($ip, FILTER_VALIDATE_IP)) {
            return $ip;
        } else {
            return 'Unable to determine IP address';
        }
    }
    • HTTP_CLIENT_IP: 一般用于检查客户端的真实 IP 地址,如果客户端通过代理服务器访问,可能会存在这个字段。
    • HTTP_X_FORWARDED_FOR: 这个字段通常会包含代理服务器的 IP 地址链,可能包含多个 IP 地址。这里通过 explode 分割并选择列表中的最后一个 IP 地址作为真实 IP。
    • REMOTE_ADDR: 如果上述两个字段都没有,则使用 REMOTE_ADDR,这是标准的获取客户端 IP 地址的方式。
    • 使用 filter_var 函数验证 IP 地址的有效性。
  3. 获取用户真实 IP 地址:

    $user_ip = getRealIpAddr();
  4. 返回 JSON 格式的 IP 地址:

    $response = array(
        'ip' => $user_ip
    );
    
    echo json_encode($response);
    • 将获取的 IP 地址存储在数组 $response 中。
    • 使用 json_encode 函数将数组编码为 JSON 格式并输出。

获取用户UA

具体代码如下:

<?php

// 设置响应头,允许跨域访问
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// 检查是否有 User Agent 信息
if(isset($_SERVER['HTTP_USER_AGENT'])) {
    // 获取用户的 User Agent 信息
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    // 返回 JSON 格式的 User Agent 信息
    echo json_encode(array("user_agent" => $user_agent));
} else {
    // 如果没有 User Agent 信息,返回错误信息
    echo json_encode(array("error" => "User Agent not found"));
}

?>

AI生成的代码详解

  1. 设置响应头:

    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    • Access-Control-Allow-Origin: *: 允许所有域名访问此 PHP 脚本。这是为了支持跨域请求,适用于前端应用通过 AJAX 从不同域名访问此脚本。
    • Content-Type: application/json; charset=UTF-8: 设置响应内容的 MIME 类型为 application/json,并指定字符集为 UTF-8,表明返回的数据格式是 JSON,且使用 UTF-8 编码。
  2. 检查 HTTP_USER_AGENT:

    if(isset($_SERVER['HTTP_USER_AGENT'])) {
    • 检查 $_SERVER['HTTP_USER_AGENT'] 是否被设置,HTTP_USER_AGENT 包含了发起请求的浏览器或客户端的信息。
  3. 获取和返回 User Agent 信息:

    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    echo json_encode(array("user_agent" => $user_agent));
    • 如果 HTTP_USER_AGENT 存在,获取其值,并将其存储在数组中,然后使用 json_encode 函数将数组编码为 JSON 格式并输出。
  4. 处理未找到 User Agent 的情况:

    echo json_encode(array("error" => "User Agent not found"));
    • 如果 HTTP_USER_AGENT 不存在,返回一个包含错误信息的 JSON 对象。

网易热歌榜API

具体代码如下

<?php

// 发送 HTTP 请求获取数据
$url = 'http://music.163.com/api/playlist/detail?id=3778678'; // 热歌榜API接口
$response = file_get_contents($url);

// 如果使用 curl 库
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

if ($response === false) {
    $result = array('error' => 'Failed to fetch data from API');
} else {
    // 解析 API 响应
    $data = json_decode($response, true);

    if (!$data) {
        $result = array('error' => 'Error decoding JSON');
    } elseif (isset($data['result']['tracks'])) {
        // 处理数据
        $tracks = $data['result']['tracks'];
        $songList = array();
        foreach ($tracks as $track) {
            $songList[] = array(
                'name' => $track['name'],
                'artist' => $track['artists'][0]['name']
            );
        }
        $result = array('songs' => $songList);
    } else {
        $result = array('error' => '未找到歌曲数据');
    }
}

// 输出 JSON 数据
header('Content-Type: application/json');
echo json_encode($result);

?>

AI生成的代码详解

  1. 定义 API URL 并获取数据:

    $url = 'http://music.163.com/api/playlist/detail?id=3778678'; // 热歌榜API接口
    $response = file_get_contents($url);
    • $url: 定义了 API 接口的 URL。
    • file_get_contents($url): 发送 HTTP 请求并获取 API 的响应内容。这是一个简单的方式,但在处理更复杂的请求时可能不够灵活。
  2. 使用 cURL 获取数据:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    • curl_init(): 初始化 cURL 会话。
    • curl_setopt(): 设置 cURL 选项:

      • CURLOPT_URL: 设置请求的 URL。
      • CURLOPT_RETURNTRANSFER: 将 cURL 执行结果作为字符串返回,而不是直接输出。
    • curl_exec(): 执行 cURL 请求。
    • curl_close(): 关闭 cURL 会话。
  3. 错误处理:

    if ($response === false) {
        $result = array('error' => 'Failed to fetch data from API');
    }
    • 如果请求失败,返回一个包含错误信息的 JSON 对象。
  4. 解析和处理 API 响应:

    $data = json_decode($response, true);
    
    if (!$data) {
        $result = array('error' => 'Error decoding JSON');
    } elseif (isset($data['result']['tracks'])) {
        $tracks = $data['result']['tracks'];
        $songList = array();
        foreach ($tracks as $track) {
            $songList[] = array(
                'name' => $track['name'],
                'artist' => $track['artists'][0]['name']
            );
        }
        $result = array('songs' => $songList);
    } else {
        $result = array('error' => '未找到歌曲数据');
    }
    • json_decode($response, true): 将 JSON 格式的响应解码为 PHP 数组。
    • 错误处理:

      • 如果解码失败,返回包含错误信息的 JSON 对象。
      • 如果响应中包含 resulttracks,则提取歌曲信息:

        • 遍历 tracks 数组,将每首歌的名字和第一位艺术家的名字添加到 songList 数组中。
      • 如果没有找到歌曲数据,返回错误信息。
  5. 输出 JSON 数据:

    header('Content-Type: application/json');
    echo json_encode($result);
    • header('Content-Type: application/json'): 设置响应的内容类型为 JSON。
    • json_encode($result): 将结果数组编码为 JSON 格式并输出。
Description of the image
Description of the image
最后修改:2024 年 09 月 21 日
如果觉得我的文章对你有用,请随意赞赏