Please wait for 15 seconds...

Wednesday, 14 November 2012



Javascript AJAX do not support cross domain communication. So if you need to call a web page which is hosted on different server, you have only option. You have to call that URL in PHP. There could be two method for it. First file_get_contents() and second through CURL.

file_get_contents() is very easy to use but there is one problem with it. If the web server is using SSL for data encryption then URL will be something like this

http://www.thirdpartysite.com/pageone.php




When you call above URL in file_get_contents() it will not give you desired result. In most cases it returns FALSE.

So I would recommend you to use CURL. In CURL you can disable SSL verification so third party server will be able to give you desired result. You have to write about 10 lines of code and you are ready to go.

Before you initialize CURL check if it is enabled on your server. Create php file get_data.php and copy n paste below code in it.

get_data.php

if(!function_exists('curl_init')){
exit('Seems you did not enable curl on your server');
}

Open get_data.php in your browser and check if CURL is enabled on your server. If there is no message on the screen then you are good.

Now copy n paste below code at the bottom in get_data.php.

function getPageData($url){
    $ch = curl_init();
    $timeout = 10;
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

I am setting here CURL maximum execution timeout to 10 seconds. You can modify it later. Because PHP default maximum execution time is 30 seconds so it is recommended to set 10 seconds for CURL.

Now copy n paste below example at the bottom of the page and reload get_data.php in your browser.

echo "<p>Page Data</p>";
$url = "http://www.google.co.in";
echo getPageData($url);


Posted by Atul Prasad Gupta

0 comments:

Post a Comment

Subscribe Techsirius

Techsirius on Facebook