Check if links are broken in php

前端 未结 4 1691
盖世英雄少女心
盖世英雄少女心 2020-12-05 01:00

I wonder if there is any good PHP script (libraries) to check if link are broken? I have links to documents in a mysql table and could possibly just check if the link leads

4条回答
  •  醉酒成梦
    2020-12-05 01:43

    You can check for broken link using this function:

    function check_url($url) {
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        $headers = curl_getinfo($ch);
        curl_close($ch);
    
        return $headers['http_code'];
    }
    

    You need to have CURL installed for this to work. Now you can check for broken links using:

    $check_url_status = check_url($url);
    if ($check_url_status == '200')
       echo "Link Works";
    else
       echo "Broken Link";
    

    Also check this link for HTTP status codes : HTTP Status Codes

    I think you can also check for 301 and 302 status codes.

    Also another method would be to use get_headers function . But this works only if your PHP version is greater than 5 :

    function check_url($url) {
       $headers = @get_headers( $url);
       $headers = (is_array($headers)) ? implode( "\n ", $headers) : $headers;
    
       return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
    }
    

    In this case just check the output :

    if (check_url($url))
       echo "Link Works";
    else
       echo "Broken Link";
    

    Hope this helps you :).

提交回复
热议问题