Skip to content

EXIF & Metadata Stripper — PHP source

View and strip GPS, camera, date, and software metadata from photos entirely in your browser. Download a clean copy.

This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.

<?php
/**
 * exif-stripper — EXIF / XMP / IPTC metadata reader + stripper for JPEG and PNG buffers.
 *
 * Language: PHP 7.4+ (standard library only — unpack(), no EXIF extension).
 * CosmoDev polyglot showcase port of the `exif-stripper` tool, ported from
 * src/lib/exif-stripper.ts.
 *
 * Why this file exists: every photo is a small surveillance report — GPS
 * coordinates, timestamps, serial numbers — embedded in standard metadata
 * segments. Both binary containers are parsed by hand with unpack(), exactly
 * as the TS reference does (deliberately NOT ext-exif, which is optional and
 * reads less), and stripping rebuilds the file *without* those segments while
 * copying image data byte-for-byte, so JPEG stripping is lossless. PHP strings
 * are raw byte buffers, so they stand in for the TS ArrayBuffer directly;
 * every read is bounds-checked so a corrupted file yields whatever parsed.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

namespace CosmoDev\ExifStripper;

/**
 * Everything the parser can surface, plus the rebuilt metadata-free image.
 * All fields start null / '' and stay null when absent or malformed.
 */
final class ExifMetadata
{
    public ?string $cameraMake = null;
    public ?string $cameraModel = null;
    public ?string $software = null;
    public ?string $dateTime = null;
    public ?float $gpsLatitude = null;   // decimal degrees, negative for S / W
    public ?float $gpsLongitude = null;
    public ?int $imageWidth = null;
    public ?int $imageHeight = null;
    public ?int $orientation = null;     // EXIF orientation 1-8
    public ?float $exposureTime = null;  // seconds (0.004 = 1/250 s)
    public ?float $fNumber = null;
    public ?int $iso = null;
    public ?float $focalLength = null;   // millimetres
    public string $stripped = '';        // input with every metadata segment removed
}

const PNG_SIGNATURE = "\x89PNG\r\n\x1a\n";
const EXIF_SIGNATURE = "Exif\0\0";
const IPTC_SIGNATURE = 'Photoshop 3.0' . "\0";
const XMP_SIGNATURES = ['http://ns.adobe.com/xap/1.0/', 'http://ns.adobe.com/xmp/extension/'];

/** EXIF field type -> byte size per component. */
const TYPE_SIZE = [1 => 1, 2 => 1, 3 => 2, 4 => 4, 5 => 8, 7 => 1, 9 => 4, 10 => 8];

const TYPE_ASCII = 2;
const TYPE_SHORT = 3;
const TYPE_LONG = 4;
const TYPE_RATIONAL = 5;

// IFD0 / Exif SubIFD / GPS IFD tag numbers.
const TAG_IMAGE_WIDTH = 0x0100;
const TAG_IMAGE_HEIGHT = 0x0101;
const TAG_MAKE = 0x010F;
const TAG_MODEL = 0x0110;
const TAG_ORIENTATION = 0x0112;
const TAG_SOFTWARE = 0x0131;
const TAG_DATE_TIME = 0x0132;
const TAG_EXIF_IFD_POINTER = 0x8769;
const TAG_GPS_IFD_POINTER = 0x8825;
const TAG_EXPOSURE_TIME = 0x829A;
const TAG_F_NUMBER = 0x829D;
const TAG_ISO = 0x8827;
const TAG_DATE_TIME_ORIGINAL = 0x9003;
const TAG_FOCAL_LENGTH = 0x920A;
const TAG_GPS_LAT_REF = 0x0001;
const TAG_GPS_LAT = 0x0002;
const TAG_GPS_LON_REF = 0x0003;
const TAG_GPS_LON = 0x0004;

/** Unsigned 16-bit big-endian read ('n' unpack code); null past the end. */
function u16be(string $b, int $off): ?int
{
    if ($off < 0 || $off + 2 > strlen($b)) {
        return null;
    }
    return unpack('n', substr($b, $off, 2))[1];
}

/** Unsigned 32-bit read with an explicit byte order ('V' little / 'N' big). */
function u32(string $b, int $off, bool $little): ?int
{
    if ($off < 0 || $off + 4 > strlen($b)) {
        return null;
    }
    return unpack($little ? 'V' : 'N', substr($b, $off, 4))[1];
}

function isJpeg(string $b): bool
{
    return strlen($b) >= 2 && $b[0] === "\xFF" && $b[1] === "\xD8";
}

function isPng(string $b): bool
{
    return strlen($b) >= 8 && substr($b, 0, 8) === PNG_SIGNATURE;
}

function hasSignature(string $b, int $off, string $sig): bool
{
    return $off >= 0 && $off + strlen($sig) <= strlen($b)
        && substr_compare($b, $sig, $off, strlen($sig)) === 0;
}

/**
 * Degrees/minutes/seconds + hemisphere reference -> signed decimal degrees.
 */
function formatGpsCoordinate(array $degrees, string $ref): float
{
    [$deg, $min, $sec] = array_pad($degrees, 3, 0);
    $decimal = $deg + $min / 60 + $sec / 3600;

    return $ref === 'S' || $ref === 'W' ? -$decimal : $decimal;
}

/**
 * Walk length-prefixed JPEG markers from the SOI up to SOS/EOI. Returns
 * [marker, start, end, payloadStart] tuples, or null when the structure is
 * corrupted mid-walk.
 *
 * @return list<array{int, int, int, int}>|null
 */
function collectJpegSegments(string $b): ?array
{
    $segments = [];
    $off = 2;
    while ($off + 2 <= strlen($b)) {
        if ($b[$off] !== "\xFF") {
            return null;
        }
        if ($b[$off + 1] === "\xFF") {  // padding fill byte before the real marker
            ++$off;
            continue;
        }
        $marker = ord($b[$off + 1]);
        // Standalone markers carry no length field (TEM, RSTn, SOI, EOI).
        if ($marker === 0x01 || ($marker >= 0xD0 && $marker <= 0xD9)) {
            $segments[] = [$marker, $off, $off + 2, $off + 2];
            if ($marker === 0xD9) {
                break;
            }
            $off += 2;
            continue;
        }
        $size = u16be($b, $off + 2);  // includes the 2 length bytes itself
        if ($size === null || $size < 2 || $off + 2 + $size > strlen($b)) {
            return null;
        }
        $segments[] = [$marker, $off, $off + 2 + $size, $off + 4];
        if ($marker === 0xDA) {  // SOS - entropy data follows, no more segments
            break;
        }
        $off += 2 + $size;
    }

    return $segments;
}

function isJpegMetadataSegment(string $b, array $seg): bool
{
    [$marker, , , $payload] = $seg;
    if ($marker === 0xE1) {
        return hasSignature($b, $payload, EXIF_SIGNATURE)
            || count(array_filter(XMP_SIGNATURES, fn (string $sig): bool => hasSignature($b, $payload, $sig))) > 0;
    }
    // APP13 is IPTC ("Photoshop 3.0\0" + 8BIM records) - always metadata.
    return $marker === 0xED && hasSignature($b, $payload, IPTC_SIGNATURE);
}

/**
 * A TIFF block plus the byte order taken from its BOM ("II"/"MM").
 *
 * @return array{string, bool}|null [bytes, littleEndian]
 */
function openTiff(string $tiffBytes): ?array
{
    $two = substr($tiffBytes, 0, 2);
    if ($two === 'II') {
        return [$tiffBytes, true];
    }
    if ($two === 'MM') {
        return [$tiffBytes, false];
    }

    return null;
}

/** Inline value field when it fits in 4 bytes, else the recorded offset; -1 out of bounds. */
function valueOffset(string $b, bool $little, int $entry, int $ftype, int $count): int
{
    $size = (TYPE_SIZE[$ftype] ?? 1) * $count;
    $off = $size <= 4 ? $entry + 8 : (u32($b, $entry + 8, $little) ?? -1);
    if ($off < 0 || $off + $size > strlen($b)) {
        return -1;
    }

    return $off;
}

function readAscii(string $b, bool $little, int $entry, int $ftype, int $count): ?string
{
    if ($ftype !== TYPE_ASCII || $count < 1) {
        return null;
    }
    $off = valueOffset($b, $little, $entry, $ftype, $count);
    if ($off < 0) {
        return null;
    }
    $text = rtrim(trim(substr($b, $off, $count)), "\0");

    return $text === '' ? null : $text;
}

function readNumber(string $b, bool $little, int $entry, int $ftype, int $count): ?int
{
    if ($count < 1) {
        return null;
    }
    $off = valueOffset($b, $little, $entry, $ftype, $count);
    if ($off < 0) {
        return null;
    }
    if ($ftype === TYPE_SHORT) {
        return u16be($b, $off) === null ? null : ($little ? unpack('v', substr($b, $off, 2))[1] : u16be($b, $off));
    }
    if ($ftype === TYPE_LONG) {
        return u32($b, $off, $little);
    }

    return null;
}

/** @return list<float>|null */
function readRationals(string $b, bool $little, int $entry, int $ftype, int $count): ?array
{
    if ($ftype !== TYPE_RATIONAL || $count < 1) {
        return null;
    }
    $off = valueOffset($b, $little, $entry, $ftype, $count);
    if ($off < 0) {
        return null;
    }
    $values = [];
    for ($i = 0; $i < $count; ++$i) {
        $num = u32($b, $off + $i * 8, $little) ?? 0;
        $den = u32($b, $off + $i * 8 + 4, $little) ?? 0;
        $values[] = $den === 0 ? 0.0 : $num / $den;
    }

    return $values;
}

/** First-non-null setter mirroring the TS `meta.x ??= read(...)` pattern. */
function put(object $meta, string $field, $value): void
{
    if ($value !== null && $meta->{$field} === null) {
        $meta->{$field} = $value;
    }
}

function readIfd(string $b, bool $little, int $offset, ExifMetadata $meta): void
{
    if ($offset < 8 || $offset + 2 > strlen($b)) {
        return;
    }
    $count = u16be($b, $offset) ?? 0;
    if ($offset + 2 + $count * 12 > strlen($b)) {
        return;
    }
    for ($i = 0; $i < $count; ++$i) {
        $entry = $offset + 2 + $i * 12;
        $tag = u16be($b, $entry);
        $ftype = u16be($b, $entry + 2);
        $n = u32($b, $entry + 4, $little);
        if ($tag === null || $ftype === null || $n === null) {
            return;
        }
        $num = fn (): ?int => readNumber($b, $little, $entry, $ftype, $n);
        $rat = fn (): ?array => readRationals($b, $little, $entry, $ftype, $n);
        switch ($tag) {
            case TAG_MAKE: put($meta, 'cameraMake', readAscii($b, $little, $entry, $ftype, $n)); break;
            case TAG_MODEL: put($meta, 'cameraModel', readAscii($b, $little, $entry, $ftype, $n)); break;
            case TAG_SOFTWARE: put($meta, 'software', readAscii($b, $little, $entry, $ftype, $n)); break;
            case TAG_DATE_TIME:
            case TAG_DATE_TIME_ORIGINAL: put($meta, 'dateTime', readAscii($b, $little, $entry, $ftype, $n)); break;
            case TAG_IMAGE_WIDTH: put($meta, 'imageWidth', $num()); break;
            case TAG_IMAGE_HEIGHT: put($meta, 'imageHeight', $num()); break;
            case TAG_ORIENTATION: put($meta, 'orientation', $num()); break;
            case TAG_ISO: put($meta, 'iso', $num()); break;
            case TAG_EXPOSURE_TIME: put($meta, 'exposureTime', $rat()[0] ?? null); break;
            case TAG_F_NUMBER: put($meta, 'fNumber', $rat()[0] ?? null); break;
            case TAG_FOCAL_LENGTH: put($meta, 'focalLength', $rat()[0] ?? null); break;
            case TAG_EXIF_IFD_POINTER:
                $sub = readNumber($b, $little, $entry, TYPE_LONG, 1);
                if ($sub !== null) {
                    readIfd($b, $little, $sub, $meta);
                }
                break;
            case TAG_GPS_IFD_POINTER:
                $gps = readNumber($b, $little, $entry, TYPE_LONG, 1);
                if ($gps !== null) {
                    readGpsIfd($b, $little, $gps, $meta);
                }
                break;
        }
    }
}

function readGpsIfd(string $b, bool $little, int $offset, ExifMetadata $meta): void
{
    if ($offset < 8 || $offset + 2 > strlen($b)) {
        return;
    }
    $count = u16be($b, $offset) ?? 0;
    if ($offset + 2 + $count * 12 > strlen($b)) {
        return;
    }
    $latRef = 'N';
    $lonRef = 'E';
    $lat = null;
    $lon = null;
    for ($i = 0; $i < $count; ++$i) {
        $entry = $offset + 2 + $i * 12;
        $tag = u16be($b, $entry);
        $ftype = u16be($b, $entry + 2);
        $n = u32($b, $entry + 4, $little);
        if ($tag === null || $ftype === null || $n === null) {
            return;
        }
        if ($tag === TAG_GPS_LAT_REF) {
            $ref = readAscii($b, $little, $entry, $ftype, $n);
            if ($ref !== null) {
                $latRef = strtoupper(substr($ref, 0, 1));
            }
        } elseif ($tag === TAG_GPS_LON_REF) {
            $ref = readAscii($b, $little, $entry, $ftype, $n);
            if ($ref !== null) {
                $lonRef = strtoupper(substr($ref, 0, 1));
            }
        } elseif ($tag === TAG_GPS_LAT) {
            $lat = readRationals($b, $little, $entry, $ftype, $n);
        } elseif ($tag === TAG_GPS_LON) {
            $lon = readRationals($b, $little, $entry, $ftype, $n);
        }
    }
    if ($lat !== null) {
        put($meta, 'gpsLatitude', formatGpsCoordinate($lat, $latRef));
    }
    if ($lon !== null) {
        put($meta, 'gpsLongitude', formatGpsCoordinate($lon, $lonRef));
    }
}

function parseTiff(string $tiffBytes, ExifMetadata $meta): void
{
    $t = openTiff($tiffBytes);
    if ($t === null || strlen($tiffBytes) < 8) {
        return;
    }
    [$b, $little] = $t;
    if (u16be($b, 2) !== 42) {
        return;
    }
    $first = u32($b, 4, $little);
    if ($first !== null) {
        readIfd($b, $little, $first, $meta);
    }
}

/**
 * XMP is XML; the only field surfaced is the creator tool / software, which
 * appears as e.g. <xmp:CreatorTool>Pixelmator Pro</xmp:CreatorTool>.
 */
function parseXmp(string $payload, ExifMetadata $meta): void
{
    if (preg_match('/:(?:CreatorTool|Software)>([^<]+)</', $payload, $m) === 1) {
        put($meta, 'software', trim($m[1]));
    }
}

function parseJpeg(string $b, ExifMetadata $meta): void
{
    foreach (collectJpegSegments($b) ?? [] as [$marker, $start, $end, $payload]) {
        if ($marker === 0xE1) {
            $chunk = substr($b, $payload, $end - $payload);
            if (hasSignature($b, $payload, EXIF_SIGNATURE)) {
                parseTiff(substr($chunk, strlen(EXIF_SIGNATURE)), $meta);
            } elseif (count(array_filter(XMP_SIGNATURES, fn (string $sig): bool => hasSignature($b, $payload, $sig))) > 0) {
                parseXmp($chunk, $meta);
            }
        } elseif ($marker >= 0xC0 && $marker <= 0xCF && $marker !== 0xC4 && $marker !== 0xC8
            && $marker !== 0xCC && $end - $payload >= 5) {
            // Start-of-frame header: precision(1), height(2), width(2), big-endian.
            put($meta, 'imageHeight', u16be($b, $payload + 1));
            put($meta, 'imageWidth', u16be($b, $payload + 3));
        }
    }
}

/**
 * Visits every PNG chunk (type, data, offset, length); returns the offset
 * where the walk stopped.
 *
 * @return int
 */
function eachPngChunk(string $b, callable $visit): int
{
    $off = 8;
    while ($off + 8 <= strlen($b)) {
        $length = u32($b, $off, false) ?? 0;
        if ($length > strlen($b) - $off - 12) {
            break;  // corrupted chunk
        }
        $type = substr($b, $off + 4, 4);
        $visit($type, substr($b, $off + 8, $length), $off, $length);
        $off += 12 + $length;
        if ($type === 'IEND') {
            break;
        }
    }

    return $off;
}

function parsePng(string $b, ExifMetadata $meta): void
{
    eachPngChunk($b, function (string $type, string $data, int $off, int $length) use ($b, $meta): void {
        if ($type === 'IHDR') {
            put($meta, 'imageWidth', u32($data, 0, false));
            put($meta, 'imageHeight', u32($data, 4, false));
        } elseif ($type === 'tEXt' || $type === 'iTXt') {
            parsePngTextChunk($type, $data, $meta);
        } elseif ($type === 'eXIf') {
            parseTiff($data, $meta);
        }
    });
}

function parsePngTextChunk(string $kind, string $data, ExifMetadata $meta): void
{
    $nul = strpos($data, "\0");
    if ($nul === false || $nul < 1 || substr($data, 0, $nul) !== 'Software') {
        return;
    }
    if ($kind === 'tEXt') {
        $text = substr($data, $nul + 1);
    } else {
        // iTXt: keyword\0 compressionFlag(1) method(1) langTag\0 translated\0 text.
        if (ord($data[$nul + 1]) !== 0) {
            return;  // compressed - not read
        }
        $pos = $nul + 3;
        for ($skipped = 0; $skipped < 2; ++$skipped) {  // skip lang tag + translated keyword
            $next = strpos($data, "\0", $pos);
            if ($next === false) {
                return;
            }
            $pos = $next + 1;
        }
        $text = substr($data, $pos);
    }
    $value = trim($text);
    if ($value !== '') {
        put($meta, 'software', $value);
    }
}

function stripJpeg(string $b): string
{
    $segments = collectJpegSegments($b);
    if ($segments === null) {
        return $b;  // corrupted walk - copy verbatim
    }
    $parts = [substr($b, 0, 2)];
    foreach ($segments as $seg) {
        [$marker, $start, $end, $payload] = $seg;
        if ($marker === 0xDA) {
            $parts[] = substr($b, $start);  // SOS header + entropy data + EOI, verbatim
            break;
        }
        if (!isJpegMetadataSegment($b, $seg)) {
            $parts[] = substr($b, $start, $end - $start);
        }
    }

    return implode('', $parts);
}

function stripPng(string $b): string
{
    $parts = [substr($b, 0, 8)];
    $end = eachPngChunk($b, function (string $type, string $data, int $off, int $length) use ($b, &$parts): void {
        // tEXt / iTXt / eXIf are the metadata carriers; every other chunk
        // (IHDR, PLTE, IDAT, ...) is copied byte-for-byte, CRC included.
        if ($type !== 'tEXt' && $type !== 'iTXt' && $type !== 'eXIf') {
            $parts[] = substr($b, $off, 12 + $length);
        }
    });
    if ($end < strlen($b)) {
        $parts[] = substr($b, $end);
    }

    return implode('', $parts);
}

/**
 * Rebuild the image without any metadata segment; lossless for JPEG.
 *
 * @throws \InvalidArgumentException when the buffer is too small or the
 *                                   format is neither JPEG nor PNG.
 */
function stripMetadata(string $data): string
{
    if (strlen($data) < 8) {
        throw new \InvalidArgumentException('File is too small to be a valid image.');
    }
    if (isJpeg($data)) {
        return stripJpeg($data);
    }
    if (isPng($data)) {
        return stripPng($data);
    }
    throw new \InvalidArgumentException('Unsupported format: only JPEG and PNG images are supported.');
}

/**
 * Read every supported metadata field, plus a stripped copy of the image.
 *
 * @throws \InvalidArgumentException when the buffer is too small or the
 *                                   format is neither JPEG nor PNG.
 */
function parseMetadata(string $data): ExifMetadata
{
    if (strlen($data) < 8) {
        throw new \InvalidArgumentException('File is too small to be a valid image.');
    }
    if (!isJpeg($data) && !isPng($data)) {
        throw new \InvalidArgumentException('Unsupported format: only JPEG and PNG images are supported.');
    }
    $meta = new ExifMetadata();
    $meta->stripped = stripMetadata($data);
    if (isJpeg($data)) {
        parseJpeg($data, $meta);
    } else {
        parsePng($data, $meta);
    }

    return $meta;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →