Skip to content

Instantly share code, notes, and snippets.

@natebenes
Created March 16, 2010 20:28
Show Gist options
  • Save natebenes/334460 to your computer and use it in GitHub Desktop.
Save natebenes/334460 to your computer and use it in GitHub Desktop.
<?php
// A very simple function for posting gists using cURL
function postGist($gistname,$gistextension,$gistcontents)
{
// clean POST variables
$gistname = urlencode($gistname);
$gistextension = urlencode($gistextension);
$gistcontents = urlencode($gistcontents);
// Define the API endpoint
$url = 'http://gist.github.com/gists';
// Construct the POST argument
$postargs = "file_name[gistfile1]=".$gistname."&file_ext[gistfile1]=".$gistextension."&file_contents[gistfile1]=".$gistcontents;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postargs);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
// Just return headers
curl_setopt($ch, CURLOPT_HEADER,1);
curl_setopt($ch, CURLOPT_NOBODY ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
// process $result;
$code = -1;
$newgid = -1;
// Look for the response code (200, 302, 404, etc.)
if(preg_match('/HTTP\/1\.\d+\s+(\d+)/', $result, $matches))
{
// We found one!
$code=intval($matches[1]);
}
else
{
// Something is really broke
die("failed to get header");
}
if(preg_match('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', $result, $redirmatches))
{
// Parse the response to get the id #
$tempgid = substr($redirmatches[0],-6,6);
$newgid=intval($tempgid);
}
else
{
// Gist is down?
die("failed to verify gist creation");
};
// A final check:
// the API sends a 302 moved if everything went ok.
if(! $code = 302) $newgid = -1;
postGist = $newgid;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment