PHP

Detect & Strip Byte Order Mark

admin by @admin ADMIN
7m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Some text editors prepend a UTF-8 BOM (0xEF 0xBB 0xBF) which breaks header() calls, JSON, and PHP output. Detect and strip it defensively when ingesting external files.
PHP
Raw
<?php
const UTF8_BOM = "\xEF\xBB\xBF";

function hasBom(string $s): bool {
    return strncmp($s, UTF8_BOM, 3) === 0;
}

function stripBom(string $s): string {
    return hasBom($s) ? substr($s, 3) : $s;
}

// Useful when reading user-uploaded CSV files written from Excel.
$csv = stripBom(file_get_contents('upload.csv'));
$lines = explode("\n", $csv);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.