Skip to content

Instantly share code, notes, and snippets.

@keranm
Created January 29, 2013 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keranm/4661793 to your computer and use it in GitHub Desktop.
Save keranm/4661793 to your computer and use it in GitHub Desktop.
PUT with PHP and CURL
<?php
// EXAMPLE OF PUT with PHP and CURL
//
// by Keran McKenzie
//
// NOTE this assumes you are posting JSON in a variable called $jsonString
// also assumes we have the username & password in variables
// setup Curl
$session = curl_init();
// Put requires a file to 'put' to the servier, so lets use php's TEMP file function
// to create the file so we don't have to worry about writing a file to the server
$putData = tmpfile();
// now we write the JSON string into the file
fwrite($putData, $jsonString);
// Reset the file pointer
fseek($putData, 0);
// Setup our headers so we tell the server to expect JSON
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
// We want to transfer this as a Binary Transfer
curl_setopt($session, CURLOPT_BINARYTRANSFER, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Do you want CURL to output the headers? Set to FALSE to hide them
curl_setopt($session, CURLOPT_HEADER, true);
// pass the URL to CURL
curl_setopt($session, CURLOPT_URL, $url);
// Tell CURL we are using PUT
curl_setopt($session, CURLOPT_PUT, true);
// Authenticate the user using basic auth $username and $password
curl_setopt($session, CURLOPT_USERPWD, $username.":".$password );
// Now we want to tell CURL the were the file is and it's size
curl_setopt($session, CURLOPT_INFILE, $putData);
curl_setopt($session, CURLOPT_INFILESIZE, strlen($putString));
// right all done? Lets execute this
$output = curl_exec($session);
// echo the output to the screen
echo $output;
// Clean up by closing the file and closing curl
fclose($putData);
curl_close($session);
@phil2phil
Copy link

phil2phil commented Aug 25, 2022

Line 39: $putString is undefined. Did you mean $jsonString?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment