Thursday, July 4, 2013

PUTting data fields with PHP cURL

This is a little post about how to PUT multiple data fields using the PHP cURL extension. Why I wanted to do this in the first place is beyond the scope of this post, since its quite a long story. The curl command line allows data fields to be sent with a PUT request, and I wanted to do the same from PHP. Here is a snippet of code to show how I did it.
<?php
$data 
= array(
    
"id" => 10,
    
'name' => 'Pritom K Mondal',
    
"roll" => "00+060238=25 & this would be a nice day &amp; hmm.",
    
'items' => array(
        
'Yellow Jacket',
        
'item_2' => "Red Shirt",
        
'attributes' => array(
            
'color' => "Red",
            
"Size of Shirt" => array(
                
"Normal" => "1 inch",
                
"Midium Shirt" => "10 inch"
            
)
        )
    )
);
 

$ch   curl_init("http://localhost/ck/put2.php");
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
curl_setopt($chCURLOPT_CUSTOMREQUEST"PUT"); 
curl_setopt($chCURLOPT_POSTFIELDSmakeRawQuery($data)); 
$response curl_exec($ch);
if (!
$response) {
    return 
false;
}
 

print_r($response);

function 
makeRawQuery($data$keyPrefix "")
{
    
$query "";
    foreach (
$data as $key => $value) {
        if (
is_array($value)) {
            if (
strlen($keyPrefix) > 0) {
                
$keyPrefixDummy $keyPrefix "[" $key "]";
            } else {
                
$keyPrefixDummy $key;
            }
            
$query .= makeRawQuery($value$keyPrefixDummy);
        } else {
            if (
strlen($keyPrefix) > 0) {
                
$key $keyPrefix "[" $key "]";
            }
            
$query .= $key "=" rawurlencode($value) . "&";
        }
    }
    return 
$query;
}
 

?>

put2.php

<?php
echo "RECEIVED DATA: \n"; parse_str(file_get_contents("php://input"), $post_vars);
print_r($post_vars);
echo 
"\nREQUEST METHOD: " $_SERVER['REQUEST_METHOD'];?>

And output is as following of print_r($response) in put.php:

RECEIVED DATA: 
Array
(
    [id] => 10
    [name] => Pritom K Mondal
    [roll] => 00+060238=25 & this would be a nice day &amp; hmm.
    [items] => Array
        (
            [0] => Yellow Jacket
            [item_2] => Red Shirt
            [attributes] => Array
                (
                    [color] => Red
                    [Size of Shirt] => Array
                        (
                            [Normal] => 1 inch
                            [Midium Shirt] => 10 inch
                        )

                )

        )

)

REQUEST METHOD: PUT

No comments:

Post a Comment