WP_REST_Attachments_Controller::get_filename_from_disposition()public staticWP 4.7.0

Parses filename from a Content-Disposition header value.

As per RFC6266:

content-disposition = "Content-Disposition" ":"
					   disposition-type *( ";" disposition-parm )
disposition-type    = "inline" | "attachment" | disp-ext-type
					; case-insensitive
disp-ext-type       = token
disposition-parm    = filename-parm | disp-ext-parm
filename-parm       = "filename" "=" value
					| "filename*" "=" ext-value
disp-ext-parm       = token "=" value
					| ext-token "=" ext-value
ext-token           = <the characters in token, followed by "*">

Method of the class: WP_REST_Attachments_Controller{}

No Hooks.

Return

String|null. Filename if available, or null if not found.

Usage

$result = WP_REST_Attachments_Controller::get_filename_from_disposition( $disposition_header );
$disposition_header(string[]) (required)
List of Content-Disposition header values.

Changelog

Since 4.7.0 Introduced.

WP_REST_Attachments_Controller::get_filename_from_disposition() code WP 6.6.2

public static function get_filename_from_disposition( $disposition_header ) {
	// Get the filename.
	$filename = null;

	foreach ( $disposition_header as $value ) {
		$value = trim( $value );

		if ( ! str_contains( $value, ';' ) ) {
			continue;
		}

		list( $type, $attr_parts ) = explode( ';', $value, 2 );

		$attr_parts = explode( ';', $attr_parts );
		$attributes = array();

		foreach ( $attr_parts as $part ) {
			if ( ! str_contains( $part, '=' ) ) {
				continue;
			}

			list( $key, $value ) = explode( '=', $part, 2 );

			$attributes[ trim( $key ) ] = trim( $value );
		}

		if ( empty( $attributes['filename'] ) ) {
			continue;
		}

		$filename = trim( $attributes['filename'] );

		// Unquote quoted filename, but after trimming.
		if ( str_starts_with( $filename, '"' ) && str_ends_with( $filename, '"' ) ) {
			$filename = substr( $filename, 1, -1 );
		}
	}

	return $filename;
}