检测网站友链是否可以访问

前言

在建设网站的过程中避免不了和其他网站交换友链,但是时间一长有些网站就停止运营了导致友链失效,有些网站的友链很多一个个查看太费时间。

于是我就想通过PHP来确定网站是否可以访问。此教程仅适合CoreNext 主题,其他主题 请慎重修改!

教程

请将其中的https://www.xrbk.cn 换成自己的网站

代码如下

<?php
$url = 'https://www.xrbk.cn/';
$html = file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$friend_items = $xpath->query('//div[@class="friend-item"]');

if ($friend_items->length == 0) {
    $result = ['code' => 404, 'msg' => '暂无友链'];
} else {
    $result = ['code' => 200, 'msg' => 'success', 'total' => $friend_items->length];
    $data = [];
    foreach ($friend_items as $item) {
        $name = $xpath->query('.//img[@alt]', $item)->item(0)->getAttribute('alt');
        $url = $xpath->query('.//a[@href]', $item)->item(0)->getAttribute('href');
        if (!empty($url)) {
            $status = check_url($url);
            $data[] = ['name' => $name, 'url' => $url, 'status' => $status ? 'run' : 'error'];
        }
    }
    $result['data'] = $data;
}

echo json_encode($result, JSON_UNESCAPED_UNICODE);

function check_url($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $http_code == 200;
}
THE END