Skip to content

Instantly share code, notes, and snippets.

@hmic
Last active September 24, 2021 08:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hmic/60ad53de920094db29e303199cc22f96 to your computer and use it in GitHub Desktop.
Save hmic/60ad53de920094db29e303199cc22f96 to your computer and use it in GitHub Desktop.
PHP post data and file - multipart-form-data
<?php
/*
* use like:
* httpPostDataFile(
* 'https://www.google.com/search', // the url to post to, optionally including get parameters like: ?this=that&here=there
* [
* 'q' => 'php http upload file', // post data like: <input name="q" value="php http upload file" />
* ...
* ], [
* 'image' => [ // the input name used like: <input name="image" type="file" />
* 'file' => './images/profile.jpg', // path and name of the file to upload, alternatively use 'data' below
* //'data' => 'ÿØÿà JFIF', // if file data is temporary and not available on the filesystem, you can provide it here directly
* 'name' => 'imyself.jpg', // the name of the file being uploaded as seen by the server
* 'content_type' => 'image/jpeg' // optional, defaults to plain/text
* ],
* ...
* ]
* );
*/
function httpPostDataFile($url, $post_data = null, $files = null) {
$boundary = md5(microtime());
$options = array(
// use key 'http' even if you send the request to https://...
'http' => array(
'header' => "Content-Type: multipart/form-data; boundary=" . $boundary . "\r\n",
'method' => 'POST',
),
);
if(is_array($post_data)) foreach($post_data as $name => $data) {
$options['http']['content'] .= '--' . $boundary . '
Content-Disposition: form-data; name="' . $name . '"
' . $data . '
';
}
if(is_array($files)) foreach($files as $field => $file) {
$options['http']['content'] .= '--' . $boundary . '
Content-Disposition: form-data; name="' . $field . '"; filename="' . basename($file['name']) . '"
Content-Type: ' . !isset($file['content_type']) ? 'plain/text' : $file['content_type'] . '
Content-Transfer-Encoding: base64
' . chunk_split(base64_encode(!isset($file['data']) ? file_get_contents($file['file']) : $file['data'])) . '
';
}
if(is_array($post_data) && count($post_data) || is_array($files) && count($files)) {
$options['http']['content'] .= '--' . $boundary . '--
';
}
$context = stream_context_create($options);
return file_get_contents($url, false, $context);
}
@pgooood
Copy link

pgooood commented Sep 24, 2021

you better put "\r\n" instead of line breaks

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