-
-
Save imbharat420/802126705e57538dd3729116c5d071ab to your computer and use it in GitHub Desktop.
Get all links from a website page
This file contains hidden or 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
#!/usr/bin/env php | |
<?php | |
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)'; | |
$target_url = $argv[1] ; | |
if( !$target_url ) { | |
echo PHP_EOL."You'll have to provide a full url".PHP_EOL; | |
exit(1); | |
} | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); | |
curl_setopt($ch, CURLOPT_URL,$target_url); | |
curl_setopt($ch, CURLOPT_FAILONERROR, true); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_AUTOREFERER, true); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); | |
curl_setopt($ch, CURLOPT_TIMEOUT, 10); | |
$html= curl_exec($ch); | |
if (!$html) { | |
echo "<br />cURL error number:" .curl_errno($ch); | |
echo "<br />cURL error:" . curl_error($ch); | |
exit; | |
} | |
// parse the html into a DOMDocument | |
$dom = new DOMDocument(); | |
@$dom->loadHTML($html); | |
// grab all the on the page | |
$xpath = new DOMXPath($dom); | |
$hrefs = $xpath->evaluate("/html/body//a"); | |
for ($i = 0; $i < $hrefs->length; $i++) { | |
$href = $hrefs->item($i); | |
$url = $href->getAttribute('href'); | |
if( substr( $url, 0, 1 ) == '/' ) { | |
$url = substr( $url, 1 ); | |
} | |
if ( !stristr( $url, 'http' ) && !stristr( $url, 'mailto' ) && substr( $url, 0, 1) !== "#" ) { | |
echo $url.PHP_EOL; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment