What is the method in PHP to determine if a link is broken or not?

In PHP, you can use the curl library to check if a link is broken. Here is a simple example code:

function isLinkValid($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode >= 200 && $httpCode < 400) {
        return true;
    } else {
        return false;
    }
}

$url = "https://www.example.com";
if (isLinkValid($url)) {
    echo "链接有效";
} else {
    echo "链接失效";
}

In the above code, a CURL session is first initialized using the curl_init function. Then, various options are set such as setting the return data to true, allowing redirection, setting a timeout of 10 seconds, and finally executing the curl request. Afterwards, the HTTP status code is obtained using the curl_getinfo function. If the status code falls between 200 and 399, the link is considered valid, otherwise it is invalid.

广告
Closing in 10 seconds
bannerAds