wp_generate_attachment_metadata generates 503 Service Unavailable or 500 timeout errors

I’ve been struggling for a week with this…
I was trying to upload an image with media_handle_upload but it never worked (it always timed out), so I decided to break it down to see where it failed and I wrote this:

if ( move_uploaded_file($file["tmp_name"], $target_file) ) {
    $wp_filetype = wp_check_filetype($filename, null);
    $attachment = array(
        'post_author' => $_SESSION['writer_WP_id'],
        'post_title' => $_SESSION['artist'],
        'post_status' => 'inherit',
        'post_name' => $filename,
        'post_mime_type' => $wp_filetype['type'],
        'guid' => $target_url."https://wordpress.stackexchange.com/".$filename
    );
    $image_id = wp_insert_attachment( $attachment, $target_file, null, true );
        if ( is_wp_error($image_id) && !empty( $image_id->errors ) ) {
            echo '<span class="error">There was an error inserting your image attachment. - ' . $image_id->get_error_message() .'</span><br />';
        } else {
            // The image sub-sizes are created during wp_generate_attachment_metadata().
            // This is generally slow and may cause timeouts or out of memory errors.
            $image_attachment = wp_generate_attachment_metadata( $image_id, $target_file );
            if ( !$image_attachment ) {
                echo '<span class="error">There was an error generating attachment metadata</span><br />';
            } else {
                if ( !wp_update_attachment_metadata( $image_id, $image_attachment ) ) {
                    echo '<span class="error">There was an error attaching info to your your file</span><br />';
                } else {
                    echo '<span class="success">Thank you for uploading your <b>'.str_replace('dlk','',$which_image).'</b>.</span><br />';
                    $_SESSION['ready_to_publish'] = 1; // after this the user CAN publish if they don't want to add more images
                }
            }
        }
    } else {
        echo '<span class="error">There was an error uploading your file</span><br />';
    }

The file gets uploaded (move_uploaded_file works) and gets inserted into the dB (wp_insert_attachment works) but it fails every time with 500 or 503 when it reaches wp_generate_attachment_metadata… how can I tackle this? it’s driving me mad…

0

Leave a Comment