PHP – Decode multiple MIME header fields at once using iconv_mime_decode_headers()


In PHP, iconv_mime_decode_headers() function is used to decode multiple MIME header fields at once. It is an in-built function in PHP.

Syntax

iconv_mime_decode_headers($str_headers, $int_mode, $str_encoding)

Parameter

The iconv_mime_decode_headers() function accepts three different parameters− $headers, $mode and $encoding.

  • $headers − The $header parameter is used for the encoded headers. It is a string type parameter.

  • $mode − The $mode parameter determines the behavior in the event iconv_mime_decode_headers() encounters a deformed MIME header field. We can use any combination of the following bitmasks.

  • List of bitmasks acceptable to iconv_mime_decode_headers()

    • ICONV_MIME_DECODE_STRICT
    • ICONV_MIME_DECODE_CONTINUE_ON_ERROR
    • ICONV_MIME_DECODE_STRICT -  If the iconv_mime_decode_strict is set, the given header is decoded in full conformance but this option is disabled by default due to a lot of broken mail user agents that do not follow the requirement and do not produce the correct MIME header.
    • ICONV_MIME_DECODE_CONTINUE_ON_ERROR - If the iconv_mime_decode_continue_on_error() parameter is set, it tries to ignore any grammatical errors and continues to process a given header.
  • $encoding − The encoding is an optional parameter that is used to specifies the character set to represent the result. The iconv.internal_encoding will be used if omitted or null.

Return Value

The iconv_mime_decode_headers() function returns an associative array that holds a whole set of MIME header fields specified by headers on success, or it returns False if any error arises during the decoding.

Example 1

<pre>
   <?php
      $str_headers = <<<EOF
      Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
      To: xyz@example.com
      Date: Mon, 21 Jun 2021 00:00:00 +0000
      Message-Id: <xyz@example.com>
      Received: from localhost (localhost [127.0.0.1]) by localhost
         with SMTP id xyz for <xyz@example.com>;
         Mon, 21 Jun 2021 00:00:00 +0000 (UTC)
         (envelope-from example-return-0000-xyz=xyz.com@example.com)
      Received: (qmail 0 invoked by uid 65534); 21 Mon 2005 00:00:00 +0000
      EOF;
      $headers = iconv_mime_decode_headers($str_headers, 0, "ISO-8859-1");
      print_r($headers);
   ?>
</pre>

Output

Array
(
   [Subject] => Pr�fung Pr�fung
   [To] => xyz@example.com
   [Date] => Mon, 21 Jun 2021 00:00:00 +0000
   [Message-Id] =>
   [Received] => Array
      (
         [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id xyz for ; Mon, 21 Jun 2021 00:00:00 +0000 (UTC) (envelope-from example-return-0000-xyz=xyz.com@example.com)
         [1] => (qmail 0 invoked by uid 65534); 21 Mon 2005 00:00:00 +0000
      )
)

Updated on: 21-Aug-2021

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements