I'm trying to scan all URL (i.e., from http://0.0.0.1 to http://255.255.255.255) and fetch all Titles and Description, and store them in database. I know this is the wrong method, but i'm unable to find better solution. The following code is executed as Cron Job every 5 minutes.
scan.php
#!/usr/bin/php
<?php
error_reporting(E_ALL);
$db_host = "localhost";
$db_username = "root";
$db_password = "*****"; //Connection works fine, hidden for security purpose
$db_name = "lab";
$conn = new mysqli($db_host, $db_username, $db_password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$sql="SELECT wid FROM websites";
$result=$conn->query($sql);
$num_rows=$result->num_rows;
$nrs=4228250625-$num_rows; //255*255*255*255, going in reverse order
$url_4=$nrs%255;
$nrs=$nrs/255;
$url_3=$nrs%255;
$nrs=$nrs/255;
$url_2=$nrs%255;
$nrs=$nrs/255;
$url_1=$nrs%255;
for($i=1;$i<=5;$i++){
$url=$url_1.".".$url_2.".".$url_3.".".($url_4-$i);
try{
$html = file_get_contents_curl("http://".$url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = 'Undefined';
try {
if($nodes){
$title = $nodes->item(0)->nodeValue; //#45 This is where error lies
}
}
catch (Exception $e) {
}
$description='';
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description')
$description = $meta->getAttribute('content');
}
$wtime=time();
$sql="INSERT INTO websites (`url`,`title`,`description`,`wtime`) VALUES ('$url','$title','$description','$wtime')";
mysqli_query($conn,$sql);
}
catch(Exception $e){
}
}
?>
I'm getting the following error in log file:
[17-Nov-2016 06:22:09 Etc/GMT] PHP Notice: Trying to get property of non-object in /home/roboca6g/public_html/lab/scan.php on line 48
[17-Nov-2016 06:22:10 Etc/GMT] PHP Notice: Trying to get property of non-object in /home/roboca6g/public_html/lab/scan.php on line 48
[17-Nov-2016 06:22:11 Etc/GMT] PHP Notice: Trying to get property of non-object in /home/roboca6g/public_html/lab/scan.php on line 48
Please help me solve this issue, and also if possible, suggest better method to perform similar task.