Last active
June 17, 2019 06:19
-
-
Save FabianSchmick/2a0bba3a04a65c5798948d584920a059 to your computer and use it in GitHub Desktop.
Parse (get) all links from a website
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Util; | |
class ParseLinks | |
{ | |
private $rootLink; | |
private $links = []; | |
private $deep = 0; | |
private $domain = ''; | |
private $scheme = ''; | |
private $assets; | |
public function __construct($rootLink, $assets = false) | |
{ | |
$this->rootLink = $rootLink; | |
$this->assets = $assets; | |
if (!filter_var($this->rootLink, FILTER_VALIDATE_URL)) { | |
throw new \Exception('Not a valid URL'); | |
} | |
$d = parse_url($this->rootLink); | |
$this->domain = $d['host']; | |
$this->scheme = $d['scheme']; | |
$this->recParseLink($this->rootLink); | |
} | |
public function getLinks() | |
{ | |
ksort($this->links); | |
return $this->links; | |
} | |
private function recParseLink($link) | |
{ | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_AUTOREFERER, true); | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_URL, $link); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
$html = curl_exec($ch); | |
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
$mimeType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); | |
curl_close($ch); | |
if (!$this->assets && | |
( | |
strpos($mimeType, 'image') !== false || | |
strpos($mimeType, 'video') !== false || | |
strpos($mimeType, 'pdf') !== false) | |
) { | |
return; | |
} | |
$this->links[$link] = $httpCode; | |
if ($httpCode != 200) { | |
return; | |
} | |
$this->deep++; | |
$doc = new \DOMDocument(); | |
$doc->loadHTML($html); | |
$elements = $doc->getElementsByTagName('a'); | |
foreach ($elements as $element) { | |
if (!$link = $element->getAttribute('href')) { | |
continue; | |
} | |
if ($link[0] == '/' || $link[0] == '?') { | |
$link = $this->scheme . '://' . $this->domain . $link; | |
} | |
$p_links = parse_url($link); | |
if (!isset($p_links['host']) || $p_links['host'] != $this->domain) { | |
continue; | |
} | |
if ($link && !isset($this->links[$link])) { | |
// if ($this->deep < 4) { // Maximum deep restriction | |
$this->recParseLink($link); | |
// } | |
} | |
} | |
$this->deep--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment