PHP CURL: Fetch Web Page Contents with Status Code

Basic implementation

Copy-paste this function to get contents of a web served file / document from given URL.
Note: CURL needs to be enabled on your system.

function curl_get_contents( $url ) {
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);		
	$response = curl_exec($ch);
	$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);
	return array($http_status,$response);
}

Usage example

$url = "https://www.invision-web.net/web/?source=PHP-CURL";
list($status,$html) = curl_get_contents( $url );
if ($status == 200) {
   echo "Got valid page! HTML follows:<br />".html_entities($html);
} else {
   echo "Got invalid status code for url = $url !<br/>";
}
Coding Examples, Tutorials | Posted on July 16, 2013 by .

About Kristijan Burnik

Kristijan Burnik is a Programmer and Web Developer specializing in Server-side and Client-side Technologies and Application Development on Linux Servers and Windows Desktop . Also has experience in Networking, Desktop application development as well as Android mobile application development . Experienced in Programming Languages like Java, C, C++, C#, PHP, Javascript, MySQL and somewhat in other languages like Bash, Perl & Python. Sometimes he works as a Graphical Designer for digital production as well as for printing and advertising. He dedicates his spare time writing Tech Articles on his blog in order to share his work with others, as well as to document his projects for his own use. He's also an Educator & Mentor in field of Algorithms and Programming to young programmers in Zagreb, Croatia.

Leave a Reply