Skip to content

Commit

Permalink
Improve header field generation
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Nov 24, 2024
1 parent b063031 commit b84bfcd
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ All Notable changes to `Csv` will be documented in this file

- `JsonConverter::withPrettyPrint` now accepts the `$identSize` as its unique parameter.
- Adding support for `callable` in the `Query\Constraint` namespace.
- `HttpHeaders::forFileDownload` to be inline with RFC2183 and Header name and value best practices.

### Remove

Expand Down
2 changes: 1 addition & 1 deletion src/AbstractCsvTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public function testOutputHeaders(): void
self::assertStringContainsString('content-type: text/csv', strtolower($headers[0]));
self::assertSame('content-transfer-encoding: binary', strtolower($headers[1]));
self::assertSame('content-description: File Transfer', $headers[2]);
self::assertStringContainsString('content-disposition: attachment; filename="tst.csv"; filename*=utf-8\'\'t%C3%A9st.csv', $headers[3]);
self::assertStringContainsString('content-disposition: attachment; filename="tst.csv"; filename*=UTF-8\'\'t%c3%a9st.csv', $headers[3]);
}

public function testChunkDoesNotTimeoutAfterReading(): void
Expand Down
12 changes: 9 additions & 3 deletions src/HttpHeaders.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,20 @@ final class HttpHeaders
*/
public static function forFileDownload(string $filename, string $contentType): void
{
!(str_contains($filename, '/') || str_contains($filename, '\\')) || throw new InvalidArgumentException('The filename `'.$filename.'` cannot contain the "/" and "\" characters.');
if (str_contains($filename, '/') || str_contains($filename, '\\')) {
throw new InvalidArgumentException('The filename `'.$filename.'` cannot contain the "/" or "\" characters.');
}

/** @var string $filteredName */
$filteredName = filter_var($filename, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$fallbackName = str_replace('%', '', $filteredName);
$disposition = 'attachment; filename="'.str_replace('"', '\\"', $fallbackName).'"';
$disposition = 'attachment;filename="'.str_replace('"', '\\"', $fallbackName).'"';
if ($filename !== $fallbackName) {
$disposition .= "; filename*=utf-8''".rawurlencode($filename);
$disposition .= ";filename*=UTF-8''".preg_replace_callback(
'/[%"\x00-\x1F\x7F-\xFF]/',
static fn (array $matches): string => strtolower(rawurlencode($matches[0])),
$filename
);
}

header('content-type: '.$contentType);
Expand Down

0 comments on commit b84bfcd

Please sign in to comment.