Base64 Encode and Decode in PHP, C#, and PowerShell
Table of Contents
PHP, C#/.NET, and PowerShell each have their own Base64 implementation with different function names, method signatures, and Unicode handling quirks. This is a quick reference for developers who need working code without digging through documentation — copy-paste examples for encode and decode in each language, with Unicode-safe versions and common use cases.
Base64 in PHP — base64_encode and base64_decode
PHP has built-in functions that require no imports:
<?php
// Encode
$text = "Hello, World!";
$encoded = base64_encode($text);
echo $encoded; // SGVsbG8sIFdvcmxkIQ==
// Decode
$decoded = base64_decode("SGVsbG8sIFdvcmxkIQ==");
echo $decoded; // Hello, World!
// URL-safe Base64 (for JWT, OAuth tokens)
function base64url_encode(string $data): string {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode(string $data): string {
return base64_decode(strtr($data, '-_', '+/'));
}
?>
PHP's base64_encode() handles binary data and multibyte strings correctly — no special Unicode workaround needed. The function works on raw bytes, so any string encoding passes through correctly.
Common PHP Base64 uses: encoding binary file contents for storage in JSON APIs, creating Basic Auth headers for curl requests, generating data URIs for image embedding, and decoding Base64-encoded webhook payloads.
Base64 in C# and .NET — Convert.ToBase64String
C# uses the System.Convert class for Base64 operations:
using System;
using System.Text;
// Encode string to Base64
string text = "Hello, World!";
string encoded = Convert.ToBase64String(
Encoding.UTF8.GetBytes(text)
);
Console.WriteLine(encoded); // SGVsbG8sIFdvcmxkIQ==
// Decode Base64 to string
byte[] decodedBytes = Convert.FromBase64String("SGVsbG8sIFdvcmxkIQ==");
string decoded = Encoding.UTF8.GetString(decodedBytes);
Console.WriteLine(decoded); // Hello, World!
// URL-safe Base64 (Base64Url) — no + or / characters
string urlSafe = Convert.ToBase64String(
Encoding.UTF8.GetBytes(text),
Base64FormattingOptions.None
).Replace('+', '-').Replace('/', '_').TrimEnd('=');
Always specify Encoding.UTF8 explicitly when converting strings to bytes. If you use Encoding.Default, the behavior varies by the server's regional settings — which causes subtle bugs in international deployments.
For .NET 7 and later, System.Buffers.Text.Base64 provides allocation-free APIs for high-performance scenarios. For most application code, Convert.ToBase64String is the right choice.
Base64 in PowerShell — [Convert] Class
PowerShell uses the same .NET System.Convert class under the hood:
# Encode string to Base64
$text = "Hello, World!"
$encoded = [Convert]::ToBase64String(
[System.Text.Encoding]::UTF8.GetBytes($text)
)
Write-Output $encoded # SGVsbG8sIFdvcmxkIQ==
# Decode Base64 to string
$encoded = "SGVsbG8sIFdvcmxkIQ=="
$decoded = [System.Text.Encoding]::UTF8.GetString(
[Convert]::FromBase64String($encoded)
)
Write-Output $decoded # Hello, World!
# One-liner encode (useful in pipelines)
"Hello!" | ForEach-Object {
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($_))
}
# Decode a Kubernetes secret value (pipe output through ForEach-Object)
$secret = kubectl get secret my-secret -o jsonpath='{.data.password}'
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($secret))
Common PowerShell mistake: Using [System.Text.Encoding]::Unicode instead of ::UTF8. Unicode encoding adds null bytes between every character, making the Base64 output twice as long and incompatible with tools expecting UTF-8 encoded Base64.
PowerShell — Encoding Files and Binary Data
PowerShell is often used for Base64-encoding files in CI/CD pipelines and deployment scripts:
# Encode a file to Base64 (embed binary in scripts/configs)
$filePath = "C:certsclient.pfx"
$encoded = [Convert]::ToBase64String(
[System.IO.File]::ReadAllBytes($filePath)
)
# Write to a file for use in CI/CD environment variables
$encoded | Out-File -FilePath encoded-cert.txt -NoNewline
# Decode Base64 back to file
$encoded = Get-Content encoded-cert.txt -Raw
[System.IO.File]::WriteAllBytes(
"C:certs
estored-client.pfx",
[Convert]::FromBase64String($encoded)
)
This pattern appears frequently in Azure DevOps, GitHub Actions, and Jenkins pipelines — storing a binary certificate or key file as a Base64 string in a secret variable, then decoding it during the build or deployment stage. The Base64 string is safe to store in text-based secret stores; the binary file is reconstructed at runtime.
PHP — Practical Patterns for APIs and File Handling
Common real-world PHP Base64 patterns:
<?php
// Basic Auth header for curl
$credentials = base64_encode("apiuser:apipassword");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Basic $credentials"
]);
// Encode uploaded file for API that expects Base64
if ($_FILES['document']['error'] === UPLOAD_ERR_OK) {
$fileContents = file_get_contents($_FILES['document']['tmp_name']);
$encoded = base64_encode($fileContents);
// POST $encoded as JSON field to external API
}
// Decode Base64 image from API response and save
$response = json_decode($apiResponse, true);
$imageData = base64_decode($response['image_data']);
file_put_contents('/uploads/received-image.jpg', $imageData);
?>
When handling Base64 in PHP APIs, always validate the decoded output before writing to disk or processing further. Malformed Base64 can cause base64_decode() to return false — check the return value before using it.
Ensuring Cross-Language Compatibility
When Base64 data crosses language boundaries — PHP encoding something that C# decodes, or PowerShell encoding something that Python decodes — a few rules ensure compatibility:
- Always use UTF-8 encoding for text. PHP's
base64_encodeworks on raw bytes; C# and PowerShell require you to specify the encoding explicitly. Both must use UTF-8 to produce compatible output. - Check padding. Some implementations omit the trailing
=padding. Add it back before decoding if needed: the encoded string length should be a multiple of 4. - Standard vs URL-safe. If one end sends base64url (using - and _ instead of + and /), the other end must use the URL-safe decoder. Mixing standard and URL-safe decoders causes errors.
- Test with non-ASCII strings. Verify with a string containing accented characters or emoji — this immediately surfaces encoding mismatches that ASCII-only tests miss.
When debugging cross-language Base64 issues, paste the encoded string into the free browser decoder to get a neutral reference point — it decodes UTF-8 Base64 correctly and lets you verify what the string actually contains.
Try It Free — No Signup Required
Runs 100% in your browser. No data is collected, stored, or sent anywhere.
Open Free Base64 Encoder/DecoderFrequently Asked Questions
Why does my C# Base64 output not match PHP output for the same string?
The most common cause is character encoding. If C# uses Encoding.Unicode (UTF-16) and PHP uses base64_encode on a UTF-8 string, the encoded output will differ. Always specify Encoding.UTF8 in C# to match PHP behavior.
How do I decode a Base64 string in PowerShell that was encoded in Linux?
Linux base64 command outputs UTF-8 encoded Base64. In PowerShell, decode with [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded)). If you use ::ASCII or ::Unicode instead, non-ASCII characters will be corrupted.
Is there a Base64 function in PHP that handles URL-safe encoding natively?
Not natively in PHP 8. Use the two-line conversion shown above: base64url_encode() replaces + with -, / with _, and removes padding. The php-base64url package on Composer wraps this if you prefer a library.

