Last active
November 5, 2016 22:58
-
-
Save brettz9/8752120 to your computer and use it in GitHub Desktop.
encodeRFC5987ValueChars
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
// Posted at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent | |
var fileName = 'my file(2).txt'; | |
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName); | |
console.log(header); | |
// 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); | |
} |
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
function encodeRFC5987ValueChars ($str) { | |
// See http://tools.ietf.org/html/rfc5987#section-3.2.1 | |
// 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