When users upload very large photos and memory is tight, it seems like WordPress runs out of memory – fails to resize the uploaded photos and does not create the necessary metadata (_wp_attachment_metadata
entry in wp_postmet
a is not created).
The worst part is that the user is never notified. At most I get an “HTTP error” message.
Is is possible to somehow add an error message that will warn the user and remove the inconsistent file/database entries? How come this is not standard WP behavior?
How do your users upload photos? You’re right about
register_shutdown_function
. It seems to work well in my code, though I only ever call my back-end via AJAX (I’ve also got file upload functionality), and so only need to account for this case. Here’s how I set it up in my plugin. Outside of the plugin class, somewhere at the bottom of the file, I have a function:In my plugin constructor I hook it up like this:
I’ve successfully tested it using this SO question‘s code (produces a nice fatal error). Put it somewhere inside your AJAX handler function in the back-end and watch the back-end return a nice JSON object to the front-end:
Edit: just discovered from this SO question that
register_shutdown_function
will execute pretty much every time, even if there is no error. I’ve edited the code snippet to reflect this fact.I’m gonna add this as an answer, though it’s probably not the answer you want.
The answer is “No, it is not possible”.
Out of memory errors in PHP are fatal errors. There is no recovering from a fatality, and so no way to return a useful error message.
@vancoders answer is right in general, but if you can impose restrictions on the size of the image then you can validate that the system will not fail, immediately after the image upload.
The important thing here is not to check the file size itself but rather the dimension of the image, as the amount of memory required to prpcess it is bigger when the image in bigger.