Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PUT method with PHP cUrl Library

Tags:

put

php

curl

Instead of creating a temp file on disk you can use php://temp.

$body = 'the RAW data string I want to send';

/** use a max of 256KB of RAM before going to disk */
$fp = fopen('php://temp/maxmemory:256000', 'w');

if (!$fp) 
{
    die('could not open temp memory data');
}

fwrite($fp, $body);
fseek($fp, 0); 

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));                            

The upside is no disk IO so it should be faster and less load on your server.


Hi all I got it working using this configuration:

// Start curl
$ch = curl_init();
// URL for curl
$url = "http://localhost/";

// Clean up string
$putString = stripslashes($query);
// Put string into a temporary file
$putData = tmpfile();
// Write the string to the temporary file
fwrite($putData, $putString);
// Move back to the beginning of the file
fseek($putData, 0);

// Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Binary transfer i.e. --data-BINARY
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
// Using a PUT method i.e. -XPUT
curl_setopt($ch, CURLOPT_PUT, true);
// Instead of POST fields use these settings
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));

$output = curl_exec($ch);
echo $output;

// Close the file
fclose($putData);
// Stop curl
curl_close($ch);

:)


All all that needs to be set is the custom request to reuse post method.

CURLOPT_URL=>$url,
CURLOPT_CUSTOMREQUEST=>'PUT',
CURLOPT_POSTFIELDS=>$params,