Fix External Broken links PHP

Thursday, March 7, 2013


Adding External links may not guarantee to available all time, following code will check header response before redirect the user to that particular url using the following Code.


<?php

$url = "http://www.w3lessons.com";

$user_agent = 
'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0'

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_USERAGENT,$user_agent);
curl_setopt($ch, CURLOPT_REFERER, "");
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);


// Then, after your curl_exec call:
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
curl_close($ch);


echo "<pre>";
print_r($header);

// Re
HTTP/1.1 200 OK
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 03 Jul 2012 15:28:22 GMT
ETag: "bc241f05-1aace1-4c3ee90929180"
Accept-Ranges: bytes
Content-Length: 1748193
Content-Type: application/pdf
Date: Thu, 07 Mar 2013 11:36:42 GMT
Connection: keep-alive




?>

Checking corresponding Content-Type before redirecting user help to improve user experience.




No comments:

Post a Comment