Detect base64 encoding in PHP?

In PHP, you can detect base64 encoding by analyzing the character set and using validation functions. Base64 uses only alphanumeric characters, plus signs (+), forward slashes (/), and equal signs (=) for padding.

Method 1: Using base64_decode() with Strict Mode

The most reliable method uses base64_decode() with the strict parameter set to true

<?php
function isBase64($string) {
    // Check if string is valid base64
    if (base64_decode($string, true) !== false) {
        return true;
    }
    return false;
}

// Test cases
$test_strings = [
    'SGVsbG8gV29ybGQ=',  // "Hello World" in base64
    'VGhpcyBpcyBhIHRlc3Q=',  // "This is a test" in base64
    'Not base64 encoded',
    'Invalid@#$%characters'
];

foreach ($test_strings as $string) {
    if (isBase64($string)) {
        echo "'$string' is valid base64<br>";
        echo "Decoded: " . base64_decode($string) . "<br><br>";
    } else {
        echo "'$string' is NOT valid base64<br><br>";
    }
}
?>
'SGVsbG8gV29ybGQ=' is valid base64
Decoded: Hello World

'VGhpcyBpcyBhIHRlc3Q=' is valid base64
Decoded: This is a test

'Not base64 encoded' is NOT valid base64

'Invalid@#$%characters' is NOT valid base64

Method 2: Using Regular Expression

You can also validate base64 format using pattern matching −

<?php
function isBase64Regex($string) {
    // Base64 pattern: alphanumeric + / + = for padding
    if (preg_match('/^[a-zA-Z0-9\/\r<br>+]*={0,2}$/', $string)) {
        // Additional check: try to decode
        return base64_decode($string, true) !== false;
    }
    return false;
}

$test_cases = [
    'SGVsbG8=',           // Valid base64
    'Hello123',           // Contains valid chars but not base64
    'Test@String',        // Invalid characters
    'QWJjZGVmZ2g='       // Valid base64
];

foreach ($test_cases as $test) {
    $result = isBase64Regex($test) ? 'Valid' : 'Invalid';
    echo "String: '$test' - $result base64<br>";
}
?>
String: 'SGVsbG8=' - Valid base64
String: 'Hello123' - Invalid base64
String: 'Test@String' - Invalid base64
String: 'QWJjZGVmZ2g=' - Valid base64

Method 3: Character Analysis

This method analyzes the character composition to detect base64 patterns −

<?php
function analyzeBase64($string) {
    $invalid_chars = [];
    $valid_base64_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    
    foreach (str_split($string) as $char) {
        if (strpos($valid_base64_chars, $char) === false) {
            $invalid_chars[] = $char;
        }
    }
    
    if (empty($invalid_chars)) {
        echo "String contains only base64 characters<br>";
        if (base64_decode($string, true) !== false) {
            echo "Valid base64 encoding detected<br>";
            return true;
        } else {
            echo "Characters are valid but not proper base64<br>";
        }
    } else {
        echo "Invalid characters found: " . implode(', ', array_unique($invalid_chars)) . "<br>";
    }
    return false;
}

// Test with different strings
echo "Testing 'VGVzdA==':<br>";
analyzeBase64('VGVzdA==');

echo "\nTesting 'Hello@World':<br>";
analyzeBase64('Hello@World');
?>
Testing 'VGVzdA==':
String contains only base64 characters
Valid base64 encoding detected

Testing 'Hello@World':
Invalid characters found: @

Conclusion

Use base64_decode() with strict mode for reliable base64 detection. For additional validation, combine it with regex patterns or character analysis to ensure proper base64 format.

Updated on: 2026-03-15T08:47:58+05:30

766 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements