Created
January 27, 2010 22:54
-
-
Save simensen/288242 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function curl_setopt_custom_postfields($ch, $postfields, $headers = null) { | |
$algos = hash_algos(); | |
$hashAlgo = null; | |
foreach ( array('sha1', 'md5') as $preferred ) { | |
if ( in_array($preferred, $algos) ) { | |
$hashAlgo = $preferred; | |
break; | |
} | |
} | |
if ( $hashAlgo === null ) { list($hashAlgo) = $algos; } | |
$boundary = | |
'----------------------------' . | |
substr(hash($hashAlgo, 'cURL-php-multiple-value-same-key-support' . microtime()), 0, 12); | |
$body = array(); | |
$crlf = "\r\n"; | |
$fields = array(); | |
foreach ( $postfields as $key => $value ) { | |
if ( is_array($value) ) { | |
foreach ( $value as $v ) { | |
$fields[] = array($key, $v); | |
} | |
} else { | |
$fields[] = array($key, $value); | |
} | |
} | |
foreach ( $fields as $field ) { | |
list($key, $value) = $field; | |
if ( strpos($value, '@') === 0 ) { | |
preg_match('/^@(.*?)$/', $value, $matches); | |
list($dummy, $filename) = $matches; | |
$body[] = '--' . $boundary; | |
$body[] = 'Content-Disposition: form-data; name="' . $key . '"; filename="' . basename($filename) . '"'; | |
$body[] = 'Content-Type: application/octet-stream'; | |
$body[] = ''; | |
$body[] = file_get_contents($filename); | |
} else { | |
$body[] = '--' . $boundary; | |
$body[] = 'Content-Disposition: form-data; name="' . $key . '"'; | |
$body[] = ''; | |
$body[] = $value; | |
} | |
} | |
$body[] = '--' . $boundary . '--'; | |
$body[] = ''; | |
$contentType = 'multipart/form-data; boundary=' . $boundary; | |
$content = join($crlf, $body); | |
$contentLength = strlen($content); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array( | |
'Content-Length: ' . $contentLength, | |
'Expect: 100-continue', | |
'Content-Type: ' . $contentType, | |
)); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $content); | |
} | |
?> |
Works great.
Thank you very much for sharing.
How to attach multiple file for same key
like 'attachments[][resource]' => "@./Users/sathish/Documents/error.rtf"
'attachments[][resource]' => "@./Users/sathish/Documents/error.rtf"
It would be more correct if the boundary creation was in a loop that checked to see if the boundary is in the content, if it is not then break.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works like a charm!