自用 PHP 网络 Ping 检测 API 源码分享(支持IP归属地查询)

今天分享一个轻量的网络 Ping 检测 API,纯 PHP 单文件,不需要数据库,上传到服务器就能用。支持域名解析、延迟检测、IP归属地查询,自带调用计数。


📈 接口实时调用统计(动态图表)

以下数据直接读取服务器的 ping.txt 调用计数,每次刷新页面数据都会变化:

🖥️ 接口在线测试

输入一个域名或 IP,点击检测,实时查看结果:


📌 调用示例

直接在浏览器访问以下地址即可获取 JSON 数据:

调用方式示例
检测百度https://www.yuxli.cn/api/ping.php?target=baidu.com
检测QQhttps://www.yuxli.cn/api/ping.php?target=qq.com
检测B站https://www.yuxli.cn/api/ping.php?target=bilibili.com
不传参数https://www.yuxli.cn/api/ping.php

返回 JSON 示例:

{  "success": true,  "delay": 23,  "loss": 0,  "ip": "180.101.50.242",  "location": "中国 江苏 南京",  "total_call": 62}

🛠️ 接口参数说明

参数说明
?target=baidu.com要检测的域名或IP地址
不传target返回空结果,但调用计数+1
返回格式JSON,包含 success / delay / loss / ip / location / total_call

💻 完整源码

请将以下代码保存为 ping.php,上传至你网站根目录下的 api 文件夹中,并确保该文件夹有 PHP 的写入权限(需要写入 ping.txt 计数文件)。

<?phpob_start();header("Access-Control-Allow-Origin: *");header("Content-Type: application/json; charset=utf-8");// 统计文件$countFile = __DIR__ . 'data/ping.txt';if (!file_exists($countFile)) {    file_put_contents($countFile, '0');}$total = (int)file_get_contents($countFile);$total++;file_put_contents($countFile, $total);$target = isset($_GET['target']) ? trim($_GET['target']) : '';if (empty($target)) {    ob_clean();    echo '{"success":false,"delay":0,"loss":100,"ip":"","location":"未知","total_call":'.$total.'}';    ob_end_flush();    exit;}if (stripos($target, 'http') !== false) {    ob_clean();    echo '{"success":false,"delay":0,"loss":100,"ip":"","location":"未知","total_call":'.$total.'}';    ob_end_flush();    exit;}$ip = gethostbyname($target);if ($ip === $target && !filter_var($target, FILTER_VALIDATE_IP)) {    ob_clean();    echo '{"success":false,"delay":0,"loss":100,"ip":"","location":"未知","total_call":'.$total.'}';    ob_end_flush();    exit;}// 这里用最稳的中文免费接口 ip-api.com$location = "未知";$api = "http://ip-api.com/json/{$ip}?lang=zh-CN";// 先用file_get_contents(很多主机支持)$json = @file_get_contents($api);if (!$json) {    // 不行再用curl    if (function_exists('curl_init')) {        $ch = curl_init($api);        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        curl_setopt($ch, CURLOPT_TIMEOUT, 5);        $json = curl_exec($ch);        curl_close($ch);    }}if ($json) {    $data = json_decode($json, true);    if (!empty($data['status']) && $data['status'] === 'success') {        $location = $data['country'] . ' ' . $data['regionName'] . ' ' . $data['city'];    }}// ping测速$success = false;$delay = 0;$fp = @fsockopen($ip, 80, $errno, $errstr, 2);if ($fp) {    $start = microtime(true);    usleep(100000);    fclose($fp);    $delay = round((microtime(true) - $start) * 1000);    $success = true;}$loss = $success ? 0 : 100;ob_clean();echo '{"success":'.$success.',"delay":'.$delay.',"loss":'.$loss.',"ip":"'.$ip.'","location":"'.$location.'","total_call":'.$total.'}';ob_end_flush();?>

—— 代码来源于网络整理优化,欢迎测试使用 ——

1 条评论

排序
  1. 雨瞑

添加新评论

验证码

文章目录