Skip to content

Instantly share code, notes, and snippets.

@bladeofsteel
Created May 6, 2015 19:43
Show Gist options
  • Save bladeofsteel/8c9682de9202e8b2b914 to your computer and use it in GitHub Desktop.
Save bladeofsteel/8c9682de9202e8b2b914 to your computer and use it in GitHub Desktop.
Upload file with basic auth by file_get_contents
<?php
$boundary = '--------------------------' . microtime(true);
$header = [
sprintf("Authorization: Basic %s", base64_encode($username . ':' . $password)),
"Content-Type: multipart/form-data; boundary=" . $boundary,
];
$file_contents = file_get_contents($file);
$content = "--" . $boundary."\r\n".
"Content-Disposition: form-data; name=\"" . 'form[fileUpload]' . "\"; filename=\"" . basename($file) . "\"\r\n" .
"Content-Type: application/x-gzip\r\n\r\n" .
$file_contents . "\r\n";
$content .= "--".$boundary."\r\n".
"Content-Disposition: form-data; name=\"form[name]\"\r\n\r\n".
"$complect\r\n";
$content .= "--".$boundary."\r\n".
"Content-Disposition: form-data; name=\"form[format]\"\r\n\r\n".
"json\r\n";
$content .= "--".$boundary."--\r\n";
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $header),
'content' => $content,
]
]);
$result = file_get_contents($url, false, $context);
@terremoth
Copy link

Thanks a lot, I was searching the web for how to do that with files!

@bladeofsteel
Copy link
Author

U r welcome

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