Showing posts with label php curl. Show all posts
Showing posts with label php curl. Show all posts

Thursday, December 19, 2013

SOAP request in PHP with CURL

Php code to soap action via curl:


<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>'.
    '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'.
    ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"'.
    ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'.
        '<soap:Body>'.
            '<GetShirtInfo xmlns="http://api.soap.website.com/WSDL_SERVICE/">'.
                '<ItemId>15</ItemId>'.
            '</GetShirtInfo>'.
        '</soap:Body>'.
    '</soap:Envelope>';

$url = "https://api.soap.website.com/soap.asmx?wsdl";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

$headers = array();
array_push($headers, "Content-Type: text/xml; charset=utf-8");
array_push($headers, "Accept: text/xml");
array_push($headers, "Cache-Control: no-cache");
array_push($headers, "Pragma: no-cache");
array_push($headers, "SOAPAction: http://api.soap.website.com/WSDL_SERVICE/GetShirtInfo");
if($xml != null) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml");
    array_push($headers, "Content-Length: " . strlen($xml));
}
curl_setopt($ch, CURLOPT_USERPWD, "user_name:password"); /* If required */
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
?>

And output would be like this:


<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <ShirtInfoResponse
            xmlns="http://api.soap.website.com/WSDL_SERVICE/">
            <ShirtInfo>
                <ItemId>15</ItemId>
                <ItemName>Some Item Name</ItemName>
                <ItemPrice>658.7</ItemPrice>
                <ItemCurrency>AUD</ItemCurrency>
            </ShirtInfo>
        </ShirtInfoResponse>
    </soap:Body>
</soap:Envelope>

Thursday, December 5, 2013

POSTing json data with php cURL


<?php
$params = array(
    "id" => 1,
    "name" => "Pritom Kumar Mondal"
);
$param = json_encode($params);
$ch   = curl_init("http://localhost/api_server/user");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($param))
);
$response = curl_exec($ch);
print_r($response);
?>

Monday, August 19, 2013

Downloading a Remote File With cURL and PHP

cURL is a great tool to help you connect to remote web sites, making it easy to post forms, retrieve web pages, or even to download files. In this PhpRiot Snippet I'll show you how you can download a file straight to disk using cURL.
Note: To simplify our key points in this article we don't perform any error checking on the cURL requests. You should always do so; the curl_getinfo function is extremely useful for this.
If you use basic options when executing a cURL request, the returned data will be output directly. If instead you want to assign the response to a PHP variable you would specify the CURLOPT_RETURNTRANSFER option.
You can then read the response and write it to disk, as shown in the following listing. The $path variable is the location on the server where you want to write the file.
Listing 1 Downloading a file and saving it with file_put_contents() (listing-1.php)
<?php 
    set_time_limit(0); 
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    $data = curl_exec($ch);
 
    curl_close($ch);
 
    file_put_contents($path, $data);
?>
There is however a problem with this code. If the file you're downloading is quite large, the entire contents must be read into memory before being written to disk. Doing so can result in your script breaking down due to exceeding the memory limit.
Note: Even if your memory limit is set extremely high, you would be putting unnecessary strain on your server by reading in a large file straight to memory.
Therefore, you should let cURL do the hard work by passing to it a writable file stream. You can do this using the CURLOPT_FILE option.
Note: Because we'll be writing to a file you no longer specify the CURLOPT_RETURNTRANSFER option.
To do this you must first create a new file pointer using fopen(). Next we pass this file pointer to cURL and perform the request. Finally, we close the file pointer.
Listing 2 Using cURL to download straight to a file stream (listing-2.php)
<?php     
    set_time_limit(0); 
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path/to/a-large-file.zip';
 
    $fp = fopen($path, 'w');
 
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
 
    $data = curl_exec($ch);
 
    curl_close($ch);
    fclose($fp);
?>
That's all there is to it. You can now download files without worrying about exceeding PHP's memory limit.

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