PHP Code

Get a remote page with PHP

This code processes, retrieves and returns all the code from a remote page/URL. It uses fsockopen(), but alternately you could use cURL if it's available on your hosting server. It returns an empty string if the URL was bad or the page couldn't be retrieved.



function get_page($url) {
	$page = "";
	
	// get URL in right format
	$url_stuff 	= parse_url($url);
	$port	 	= isset($url_stuff['port']) ? $url_stuff['port'] : 80;
	if($url_stuff['host']=="") return ""; // catch malformed URLs
	
	$fp = fsockopen($url_stuff['host'], $port, $errno, $errstr, 30);
	if (!$fp) {
		$err_msg = "$errstr ($errno)\n";
	} else {
		$out  = "GET " . $url_stuff['path'] . " HTTP/1.1\r\n";
		$out .= "Host: " . $url_stuff['host'] . "\r\n";
		$out .= "Connection: Close\r\n\r\n";
			
		fwrite($fp, $out);
		while (!feof($fp)) {
			$page .= fgets($fp, 128);
		}
		fclose($fp);
	}
	return $page;
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image