Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP – Encode string for MIME header using mb_encode_mimeheader()
In PHP, mb_encode_mimeheader() function is used to encode a string for MIME (Multipurpose Internet Mail Extensions) header. It encodes a given string by the MIME header encoding scheme, which is essential for email headers containing non-ASCII characters.
Syntax
string mb_encode_mimeheader(
string $string,
?string $charset = null,
?string $transfer_encoding = null,
string $newLine = "\r<br>",
int $indent = 0
)
Parameters
The mb_encode_mimeheader() function accepts five parameters −
$string − The string to encode. Its encoding should be the same as mb_internal_encoding()
$charset − The character set name in which the string is represented (optional, defaults to internal encoding)
$transfer_encoding − The MIME encoding scheme. Should be "B" (base64) or "Q" (Quoted-printable). Defaults to "B"
$newLine − The end-of-line (EOL) marker for line-folding (defaults to "\r
")$indent − Indentation of the first line (defaults to 0)
Return Value
Returns a converted version of the string that is represented in ASCII format suitable for MIME headers.
Example 1: Basic Email Header Encoding
Here's how to encode a string for an email header ?
<?php $name = "Online tutorials"; $mbox = "user"; $domain = "example.com"; $addr = mb_encode_mimeheader($name, "UTF-8", "Q") . " <" . $mbox . "@" . $domain . ">"; echo $addr; ?>
Online tutorials <user@example.com>
Example 2: Encoding Unicode Characters
This example shows how to encode special Unicode characters ?
<?php
$string = "?"; // Arrow symbol
mb_internal_encoding("UTF-8");
echo mb_encode_mimeheader($string, 'UTF-8', 'B');
?>
=?UTF-8?B?4oaS?=
Example 3: Comparing Encoding Methods
Let's compare Base64 (B) and Quoted-Printable (Q) encoding ?
<?php $subject = "Café Newsletter"; echo "Base64 (B): " . mb_encode_mimeheader($subject, 'UTF-8', 'B') . "<br>"; echo "Quoted-Printable (Q): " . mb_encode_mimeheader($subject, 'UTF-8', 'Q'); ?>
Base64 (B): =?UTF-8?B?Q2Fmw6kgTmV3c2xldHRlcg==?= Quoted-Printable (Q): =?UTF-8?Q?Caf=C3=A9_Newsletter?=
Common Use Cases
Email Subject Lines − Encoding non-ASCII characters in email subjects
From/To Headers − Encoding names in email addresses
Custom Headers − Any email header containing special characters
Conclusion
The mb_encode_mimeheader() function is essential for properly encoding email headers with non-ASCII characters. Use Base64 encoding for binary data and Quoted-Printable for mostly ASCII text with occasional special characters.
