Skip to content

Instantly share code, notes, and snippets.

@mattweg-zz
Created October 13, 2010 07:34
Show Gist options
  • Save mattweg-zz/623638 to your computer and use it in GitHub Desktop.
Save mattweg-zz/623638 to your computer and use it in GitHub Desktop.
<?php
App::import('Core', array('Media', 'HttpSocket'));
class UploadSocket extends HttpSocket {
/**
* upload function
* allows posting of multipart form data (aka file uploads)
*
* @return result string
* @author Matt Weg
* @param mixed $uri standard HttpSocket uri, like in post() or get()
* @param array $files keyed paths to files to be posted, can be local or http path, like array('data[Model][upload]'=>'/path/to/file.ext')
* @param array $data keyed form data to be posted, must be only one demension, like array('data[Model][field]'=>'value')
*
**/
function upload($uri, $files, $data = array() ) {
// The boundary string is used to identify the different parts of a
// multipart http request
$boundaryString = String::uuid();
// building the form and file data into the body of the request
$body = "--$boundaryString\r\n";
//regular form data is prepared for posting
foreach($data as $name=>$value) {
$body.= "Content-Disposition: form-data; name=\"{$name}\"\r\n";
$body.= "\r\n";
$body.= "{$value}\r\n";
$body .= "--$boundaryString\r\n";
}
//getting availble Content-Type from cake's MediaView
$media = new MediaView();
//file data is prepared for posting
foreach($files as $name=>$path) {
$path_parts = pathinfo($path);
if(empty($path_parts['basename'])) break;
if(!empty($media->mimeType[$path_parts['extension']])) {
$mimeType = $media->mimeType[$path_parts['extension']];
} else {
$mimeType = 'text/plain';
}
$body.= "Content-Disposition: form-data; name=\"{$name}\"; filename=\"{$path_parts['basename']}\"\r\n";
$body.= "Content-Type: {$mimeType}\r\n";
if(!strstr($mimeType,'text')) {
$body.= "Content-Transfer-Encoding: binary\r\n";
}
$body.= "\r\n";
$body.= @file_get_contents($path)."\r\n";
$body.= "--$boundaryString\r\n";
}
//manually building the request to HttpSocket
$request = array(
'method'=>'POST',
'uri'=>$uri,
'header' => array(
'Content-Type' => 'multipart/form-data; boundary="' . $boundaryString . '"',
),
'body' => $body,
);
return $this->request($request);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment