Beqa
Beqa

Reputation: 99

Check if an external url is working PHP or JS

I have a php numeric array that includes 1000+ external links. Can you please help me figure out a PHP or JS function that will loop through every link and check if it's working or not? To create an array and include links that are no longer working.

For now I'm using this code:

$links = array(
    'http://google.com',
    'http://example.com',
    'http://awkrlalrno1in01n2rn12r12r.com',
    'http://112om1om1om.ru'
);

foreach($links as $link) {
    if($file_headers = @get_headers($link)) {
        if(strpos($file_headers[0],'404') !== false) {
            $toDeleteLinks[] = $link;
        }
    }elseif($handle = curl_init($link)) {
        curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
        //Get the HTML or whatever is linked in $url.
        $response = curl_exec($handle);
        //Check for 404 (file not found).
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
        if($httpCode == 0) {
            $toDeleteLinks[] = $link;
        }
        curl_close($handle);
    }
}

if(isset($toDeleteLinks)) {
    echo '<pre>';
    print_r($toDeleteLinks);
    echo '</pre>';
}

but it gives a 500 Internal Server Error.. seems like server is unable to handle so much requests, since I've tried to create an array with 4 links, 2 - correct links, 2 incorrect ones and the function works as a charm.

I'm about to pull my hears out of my head, so please help :D Thanks in advance!

Upvotes: 0

Views: 209

Answers (0)

Related Questions