PHP CURL and json encode and decode..
HI , this is very simple but hard to start using CURL in php
1. This is use to make http request to other sites like
you can download data from other sites or make API calls to fetch some data like (Facebook's graph api).
Before we start we have to check if CURL is enabled or not.
to check
user
1.
2.
just do the
and look for the curl
3. if its not enabled then
go to your php.ini file
and uncomment this line
;extension=php_curl.dll
if still you have problem with your curl then goto this link to get help link .
Lets start some curls.
Before we can do anything with a cURL request, we need to first instantiate an instance of cURL - we can do this by calling the function
curl with cookies
1. This is use to make http request to other sites like
you can download data from other sites or make API calls to fetch some data like (Facebook's graph api).
Before we start we have to check if CURL is enabled or not.
to check
user
1.
<?php
function _isCurl(){
if(function_exists('curl_init')){
echo "Yes! we have curl";
}
}
2.
just do the
<?php
php_info();
and look for the curl
3. if its not enabled then
go to your php.ini file
and uncomment this line
;extension=php_curl.dll
if still you have problem with your curl then goto this link to get help link .
Lets start some curls.
Before we can do anything with a cURL request, we need to first instantiate an instance of cURL - we can do this by calling the function
curl_init();
, which returns a cURL resource. Settings
Once we've got a cURL resource, we can begin to assign some settings, below is a list of some of the core ones that I set
CURLOPT_RETURNTRANSFER
- Return the response as a string instead of outputting it to the screenCURLOPT_CONNECTTIMEOUT
- Number of seconds to spend attempting to connectCURLOPT_TIMEOUT
- Number of seconds to allow cURL to executeCURLOPT_USERAGENT
- Useragent string to use for requestCURLOPT_URL
- URL to send request toCURLOPT_POST
- Send request asPOST
CURLOPT_POSTFIELDS
- Array of data to POST in request
We can set a setting by using the
curl_setopt()
method, which takes three parameters, the cURL resource, the setting and the value. So, to set the URL that we're sending the request to as http://testcURL.com:$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://testcURL.com');
As mentioned, we can set the URL by sending a parameter through when getting the cURL resource:
$curl = curl_init('http://testcURL.com');
It is possible to set multiple settings at one time by passing through an array of settings and values to the function
curl_setopt_array()
:$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://testcURL.com'
));
Sending request
When all of the options are sent, and the request is ready to send, we can call the
curl_exec()
method which will execute the cURL request. This function can return three different things:false
- if there is an error executing the requesttrue
- if the request executed without error andCURLOPT_RETURNTRANSFER
is set tofalse
- The result - if the request executed without error and
CURLOPT_RETURNTRANSFER
is set totrue
Using the previous example, where we are wanting to get the result back, we would use the following:
$result = curl_exec($curl);
With
$result
now containing the response from the page - which might be JSON, a string or a full blown site's HTML.Close Request
When you've sent a request and got the result back, you should look to close the cURL request so that you can free up some system resources, this is as simple as calling the
curl_close()
method which as with all other functions takes the resource as its parameter.GET Request
A
GET
request is the default request method that is used, and is very straight forward to use, infact all of the examples so far have been GET
requests. If you want to send parameters along in the request you simply append them to the URL as a query string such ashttp://testcURL.com/?item1=value&item2=value2
.So for example to send a
GET
request to the above URL and return the result we would use:// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://testcURL.com/?item1=value&item2=value2',
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
POST Request
The sole difference between the
POST
and GET
request syntax is the addition of one setting, two if you want to send some data. We'll be setting CURLOPT_POST
to true
and sending an array of data through with the setting CURLOPT_POSTFIELDS
So for example switching the above
GET
request to be a POST
request, we would use the following code:// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://testcURL.com',
CURLOPT_USERAGENT => 'Codular Sample cURL Request',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
item1 => 'value',
item2 => 'value2'
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
There you have a
POST
request that will work the same as our GET
request above and return the response back to the script so that you can use it as you want.Errors
As much as we all hate errors, you really need to take care to account for any eventuality with cURL as ultimately you will not have control over the site(s) that you are sending your request to, you cannot guarantee that the response will be in the format that you want, or that the site will even be available.
There are a few functions that you can use to handle errors and these are:
curl_error()
- returns a string error message, will be blank''
if the request doesn't fail.curl_errno()
- which will return the cURL error number which you can then look up onthis page listing error codes.
An example usage would be:
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}
You might want to look at using the setting
CURLOPT_FAILONERROR
as true
if you want any HTTP response code greater than 400 to cause an error, instead of returning the page HTML.curl_exec($theEnd);
cURL is a behemoth, and has many many possibilities.
=============== json =============
Json.
if we get some data from the facebook api like
$curl = curl("https://graph.facebook.com?access_token=<access_token>");
$result = curl_exec($curl);
//note this won't work if are on the localhost.
To solve the problem for the localhost use some curl option
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
And this wll solve the problem.
if you wan't to store the response in some variable. use
curl_setopt($curl,CURLOPT_RETURNGTRANSFER,1);
Now, we can store this into the variable.
$result = curl_exec($curl);
If we look at the type to the $result.
echo gettype($result);
o/p : string.
Convert it to the json using builtin json_decode.
$result_json = json_encode($result);
Note : if we want this as the array(nested-array)use it as
$result_array = json_encode($result,true);
To access the values from the json object do,
echo $result_json->paging->next;
For the array's we all know.
echo $result_array['paging']['next'];
Hope, this helps you guys.
Note to get access_token from the facebook use your hosted website with SSL (this is the easiest way).
curl with cookies
<?php
/* STEP 1. let’s create a cookie file */
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
/* STEP 2. visit the homepage to set the cookie properly */
$ch = curl_init ("http://somedomain.com/");
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
/* STEP 3. visit cookiepage.php */
$ch = curl_init ("http://somedomain.com/cookiepage.php");
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
/* here you can do whatever you want with $output */
?>