Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
// Posted at
var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars (str) {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
function encodeRFC5987ValueChars ($str) {
// See
// For better readability within headers, add back the characters escaped by rawurlencode but still allowable
// Although RFC3986 reserves "!" (%21), RFC5987 does not
return preg_replace_callback('@%(2[1346B]|5E|60|7C)@', function ($matches) { // !#$&+^`| are the characters matched here, respectively
return chr('0x' . $matches[1]);
}, rawurlencode($str));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment