Check if links are broken in php

前端 未结 4 1685
盖世英雄少女心
盖世英雄少女心 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:31

    You can do this in few ways:

    First way - curl

    function url_exists($url) {
        $ch = @curl_init($url);
        @curl_setopt($ch, CURLOPT_HEADER, TRUE);
        @curl_setopt($ch, CURLOPT_NOBODY, TRUE);
        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
        @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $status = array();
        preg_match('/HTTP\/.* ([0-9]+) .*/', @curl_exec($ch) , $status);
        return ($status[1] == 200);
    }
    

    Second way - if you dont have curl installed - get headers

    function url_exists($url) {
        $h = get_headers($url);
        $status = array();
        preg_match('/HTTP\/.* ([0-9]+) .*/', $h[0] , $status);
        return ($status[1] == 200);
    }
    

    Third way - fopen

    function url_exists($url){
        $open = @fopen($url,'r');
        if($handle !== false){
           return true;
        }else{
           return false;
        }
    }
    

    First & second solutions

提交回复
热议问题