The Missing Header: Why Base64 Image Decoding Results in a Corrupted File
You are sending a valid image to your PHP script, file_put_contents returns true, and the file size matches the input string. Yet, when you open the resulting .jpg, it is empty or corrupted. This specific failure mode is almost always caused by one overlooked detail: the Base64 string includes metadata that PHP's decoder does not strip away automatically.
When using the JavaScript FileReader API to read a file as DataURLs (e.g., "data:image/jpeg;base64,..."), the resulting string contains two distinct parts separated by a comma:
- The media type header (e.g.,
data:image/jpeg;base64). - The actual binary content encoded in Base64.
Your current PHP logic attempts to decode the entire string passed from JavaScript, including the header. When you run base64_decode on a string that starts with data:image/jpeg;base64, the decoder does not know how to handle the text prefix. It treats those characters as part of the binary data stream or fails silently depending on the PHP version and error handling configuration.
The result is a file that contains garbage bytes at the beginning, followed by your actual image data. While file_put_contents writes this combined blob successfully, image viewers immediately reject it because the file signature (magic number) for a JPEG is missing or corrupted. The file appears empty to a human eye, but technically, it contains invalid binary data.
Fixing the Decoder Logic
To resolve this, you must isolate the Base64 content before decoding. In PHP, explode(',', $data) can separate the header from the payload if the string is in DataURL format. However, if your JavaScript sends only the raw base64 string (without the data:... prefix), this step is unnecessary.
Given your AJAX configuration uses reader.readAsDataURL(file), you are almost certainly sending the full DataURL string. You need to strip the header before decoding:
// Retrieve the raw data from POST
$rawData = $this->input->post('photo_1');
// Check if it is a DataURL (contains 'data:' and 'base64')
if (strpos($rawData, 'data:') === 0 && strpos($rawData, ',base64,') !== false) {
// Extract just the base64 part after the comma
$base64String = explode(',', $rawData)[1];
} else {
// If it's already just base64 (no header), use the raw data directly
$base64String = $rawData;
}
// Now decode only the valid binary content
$photoTemp = base64_decode($base64String);
// Save the file
@file_put_contents($new_dir . $file . '.jpg', $photoTemp);
Handling Binary Data in Sessions and POST
There is a secondary risk to consider regarding how you are storing and retrieving this data. Your code saves the decoded content directly to the server, but if you were to store $rawData or $photoTemp into a session variable (as hinted by set_userdata in your snippet), you must be aware of PHP's default behavior.
By default, PHP sessions store data as strings. While PHP can handle binary strings, some environments or specific configurations might corrupt binary data when serializing it into the session file storage (usually php.ini settings like session.serialize_handler). If your application relies on storing this decoded image in a session to process it later, you should explicitly use the PHP_SESSION_NONE serializer or ensure your session handler supports binary data.
// If storing in session is required:
$this->session->set_userdata('upload_' . $file, $photoTemp);
// Ensure serialization is handled correctly for binary data
File Permissions and Writable Directories
Since you are using the @ symbol before mkdir and file_put_contents, you are suppressing all errors. This makes debugging difficult if the directory cannot be created due to permissions or if the file write fails for other reasons.
While file_put_contents returns true in your logs, verify that the temporary directory is actually writable by the web server user (often www-data or apache). If the directory exists but lacks write permissions, the function might behave unexpectedly depending on the specific OS and PHP version. Removing the @ suppression temporarily during development will reveal any underlying permission errors immediately.
Conclusion
The "empty image" issue stems from decoding a DataURL string that includes the MIME type header. By stripping the data:image/jpeg;base64 prefix before calling base64_decode, you ensure the binary stream matches the expected JPEG format, allowing standard image viewers to render the file correctly.
