Skip to content

Instantly share code, notes, and snippets.

@mrjnamei
Created June 14, 2017 05:56
Show Gist options
  • Save mrjnamei/9db919c7ec5da1a08b3cce9f86176eb4 to your computer and use it in GitHub Desktop.
Save mrjnamei/9db919c7ec5da1a08b3cce9f86176eb4 to your computer and use it in GitHub Desktop.
php make multipart/form-data upload file
class Multipart {
const EOL = "\r\n";
private $_data = '';
private $_mime_boundary;
public function __construct() {
$this->_mime_boundary = md5(microtime(true));
}
private function _addPartHeader() {
$this->_data .= '--' . $this->_mime_boundary . self::EOL;
}
public function addArray($data, $prefix='') {
foreach($data as $key=>$value) {
if(is_array($value)) {
if($prefix)
$this->addArray($value, $prefix.'['.$key.']');
else
$this->addArray($value, $key);
} else {
if($prefix)
$this->addPart($prefix.'['.(is_numeric($key) ? '' : $key).']', $value);
else
$this->addPart($key, $value);
}
}
}
public function addPart($key, $value) {
$this->_addPartHeader();
$this->_data .= 'Content-Disposition: form-data; name="' . $key . '"' . self::EOL;
$this->_data .= self::EOL;
$this->_data .= $value . self::EOL;
}
public function addFile($key, $filename, $type) {
$this->_addPartHeader();
$this->_data .= 'Content-Disposition: form-data; name="' . $key . '"; filename="' . basename($filename) . '"' . self::EOL;
$this->_data .= 'Content-Type: ' . $type . self::EOL;
$this->_data .= 'Content-Transfer-Encoding: binary' . self::EOL;
$this->_data .= self::EOL;
$this->_data .= file_get_contents($filename) . self::EOL;
}
public function contentType() {
return 'multipart/form-data; boundary=' . $this->_mime_boundary;
}
public function data() {
// add the final content boundary
return $this->_data .= '--' . $this->_mime_boundary . '--' . self::EOL . self::EOL;
}
}
// usage
$filedata = [
'sex' => '1' ,
'name' => 'mrjnamei'
];
$url = 'http://localhost/upload.php'; // where url you upload or another program
$file = $_FILES['file'];
$multipart = new Multipart();
// your params
$multipart->addArray($filedata);
// key , file_path , file mime-type
$multipart->addFile('file',$file['tmp_name'],$file['type']);
// make http request
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS ,$multipart->data());
curl_setopt($ch,CURLOPT_HTTPHEADER,['Content-type: ' . $multipart->contentType()]);
$response = curl_exec($ch);
return $response ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment