Teensweb
New Member
- Messages
- 352
- Reaction score
- 1
- Points
- 0
I found this cool jquery pluggin while searching the pluggins casually at the jquery site. It might be very usefull for web-admins.Here's the code:
JS:
Finally, html:
But there's a slight problem, the link checker does not work correctly with 404 pages. Is there anyway to do that?
PHP:
<?php
/**
* jQuery Link Checker
*
* http://troy.dyle.net
* Created for: http://russianwebstudio.com
* Copyright (c) 2007 Anton Sidashin
* troy [at] simix.ru
*
*/
error_reporting(E_ALL);
// this function taken from Drupal ( drupal.org )
function json($var) {
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false'; // Lowercase necessary!
case 'integer':
case 'double':
return $var;
case 'resource':
case 'string':
return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
array('\r', '\n', '\x3c', '\x3e', '\x26'),
addslashes($var)) .'"';
case 'array':
if (empty ($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
$output = array();
foreach ($var as $v) {
$output[] = json($v);
}
return '[ '. implode(', ', $output) .' ]';
}
// Otherwise, fall through to convert the array as an object.
case 'object':
$output = array();
foreach ($var as $k => $v) {
$output[] = json(strval($k)) .': '. json($v);
}
return '{ '. implode(', ', $output) .' }';
default:
return 'null';
}
}
function unique_urls($urls) {
$uurls = array();
for ($i=0; isset($urls[$i]); $i++) {
if (!in_array($urls[$i], $uurls)) {
$uurls[] = $urls[$i];
}
}
return $uurls;
}
function get_head($url, $timeout = 3) {
$info = @parse_url($url);
$fp = @fsockopen($info["host"], 80, $errno, $errstr, $timeout);
if (!$fp) {
return false;
}
// Checks the path is not empty
if (empty($info["path"])) {
// If it is empty it fills it
$info["path"] = "/";
}
$query = "";
if (isset( $info["query"] ) ) {
$query = "?".$info["query"]."";
}
$out = "HEAD ".$info["path"]."".$query." HTTP/1.0\r\n";
$out .= "Host: ".$info["host"]."\r\n";
$out .= "Connection: close \r\n" ;
$out .= "User-Agent: jQuery_LinkChecker/1.1\r\n\r\n";
// write the headers out
fwrite($fp, $out);
$html = '';
while (!feof($fp) ) {
$html .= fread($fp,8192);
}
//echo $html . '<br><br>';
//flush();
// Closes socket
fclose( $fp );
return $html;
}
// Get status code
function get_status($header) {
$headers = explode( "\r\n", $header );
unset( $header );
if (preg_match("/HTTP\/[0-9A-Za-z +]/i" ,$headers[0])) {
$status = preg_replace( "/http\/[0-9]\.[0-9]/i", "", $headers[0] );
return $status;
} else {
return 'Unknown status';
}
}
function url_exists($url, $timeout = 3) {
$html = get_head($url, $timeout);
if(empty($html)) {
return false;
}
$status = get_status($html);
if(strpos($status, '200 OK') !== FALSE) {
return true;
}
return false;
}
if(isset($_GET['links'])) {
$links = unique_urls($_GET['links']);
$timeout = (int) $_GET['timeout'];
$result = Array();
foreach ($links as $l) {
$result[] = array('href'=>rtrim($l, '/\\') , 'status'=>url_exists($l, $timeout) ? 'active' : 'inactive');
}
echo json($result);
}
?>
Code:
/**
* @author Anton Sidashin ( troy at simix dot ru )
*/
jQuery.fn.linkChecker = function(settings) {
if(!this.length) return;
settings = jQuery.extend({
linksAtOnce: 2,
checkScript: 'checklinks.php',
activeClass: 'active',
inactiveClass: 'inactive',
timeout: 3
}, settings);
var urls = Array();
this.each( function() {
urls.push(this.href);
} );
while(urls.length) {
linkSlice = Array();
for(var i = 0; i<settings.linksAtOnce; i++) {
if(urls.length) {
linkSlice.push(urls.shift());
}
}
checkLinks(linkSlice, settings, this);
}
function checkLinks(urls, settings, jLinks) {
jQuery.getJSON(settings.checkScript, {'links[]':urls, 'timeout':settings.timeout}, function(links){
for(var i = 0; i<links.length; i++) {
jLinks.filter('[href^='+ links[i].href + ']').addClass(links[i].status == 'active' ? settings.activeClass : settings.inactiveClass);
}
});
}
}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>RussianWebStudio.com</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<script Language="JavaScript"> function getXMLHTTPRequest() { try { req = new XMLHttpRequest(); } catch(err1) { try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (err2) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (err3) { req = false; } } } return req; } var http = getXMLHTTPRequest(); function checklinks() { var txt = ''; var j = document.getElementsByTagName('a').length; for(var i = 0; i < (j-1); i++) // iterate through the links { lnk = document.getElementsByTagName('a')[i]; txt = txt + lnk.href + "|"; // build the link list } lnk = document.getElementsByTagName('a')[j-1]; txt = txt + lnk.href; // no divider after last one var myurl = 'linkchecker.php?list='; myRand = parseInt(Math.random()*999999999999999); var modurl = myurl+txt+"&rand="+myRand; http.open("GET", modurl, true); http.onreadystatechange = useHttpResponse; http.send(null); } function useHttpResponse() { if (http.readyState == 4) { if(http.status != 200) { alert('Link Check Problem'); } } } </script>
<style>
.inactive {
color: #33ccff;
background: #ccffff;
}
.active {
color: #ffcc66;
background: #ffffcc;
}
</style>
</head>
<body>
<h1>jQuery Ajax Link Checker Demo</h1>
<p>Just view source of that file to see example usage. Blue means active link, red means inactive</p>
<li><a href="http://www.microsoft.com/en/us/default.aspx" class="goto">microsoft.com</a></li>
<li><a href="http://37signaghls.com/" class="goto">37signals.com</a> (99.9% online, I think :)</li>
<li><a href="http://unexistenthost.fm/" class="goto">unexistenthost.fm</a> (will be 100% offline)</li>
<li><a href="http://russianwebstudio.com/" class="goto">russianwebstudio.com</a></li>
<li><a href="http://sidashin.ru/" class="goto">sidashin.ru</a></li>
</body>
</html>