This entry was guestblogged by lorz.
Have you ever wanted to snatch the source code of a webpage in order to get some information like the title, meta-tags or even some parts of the body? For example, suppose you know a website with weather forecast. Now you would like to have some weather forecast on your website too, but you do not want to update it manually.
In this post, we are going to build a simple function to get the source code of a specific url.
We start by defining our function with a single argument: $url;
function source_code ($url) {
Now we check to see if the function named curl_init exists.
if (function_exists (’curl_init’)) {
If the condition returns true, we grab the source code with the help of curl. First we have to initiate in a variable called $curl. Simple!
$curl = @curl_init ($url);
Now we define some options for $curl. CURLOPT_HEADER is used for including the header of the page. We do not need it. So we are going to set it to FALSE.
After this, we have CURLOPT_RETURNTRANSFER which we will set to TRUE because we want our source code returned as a simple string.
After this, we have CURLOPT_FOLLOWLOCATION, and we will set it to TRUE so that the script will follow any header(”Location:”) redirects.
And the last option is CURLOPT_USERAGENT, and this will be our $_SERVER['HTTP_USER_AGENT']), the User’s browser actually.
@curl_setopt ($curl, CURLOPT_HEADER, FALSE);
@curl_setopt ($curl, CURLOPT_RETURNTRANSFER, TRUE);
@curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, TRUE);
@curl_setopt ($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
We finally get the source in $source, close curl, and return the results.
$source = @curl_exec ($curl);
@curl_close ($curl);
return $source;
Now we define our else condition, which will be used if curl_init does not exist. We simply use file_get_contents() to get the source code.
} else {
return @file_get_contents ($url);
To finish, we close both braces.
}
}
And that’s it! Now you have a fully working source code grabber script!

Hello, and welcome to my blog. My name is Tom and i am the owner of thaslayer.com. I'm 18 years old and currently in college, but also work as a freelance web designer. As you can see in my portfolio i mostly design wordpress themes, but i can handle any other design related job