1

Problem Description:

I'm developing a chat application with image upload functionality using WordPress REST API. When users attach multiple large images (3 images), the request doesn't reach the backend API endpoint, but smaller images work fine.

Key Symptoms:

  • Small 3 images work without errors
  • Large images don't trigger any backend logs or errors
  • No WordPress debug logs generated
  • Server provider confirms no server-side issues found

Environment

  • WordPress: 6.0+
  • PHP: 8.2
  • Server: Apache (shared hosting)

PHP Settings:

  • upload_max_filesize = 600M
  • post_max_size = 650M
  • max_execution_time = 500
  • max_input_time = 500
  • memory_limit = 300M
  • max_input_vars = 3000

Frontend JavaScript Code

function sendImageRequest(question, imagesArray, country, conversationHistory) {
    console.log('🖼️ Starting image analysis request with', imagesArray.length, 'images...');
    
    // Prepare image data array with pure base64
    const imageDataArray = imagesArray.map(img => {
      let pureBase64 = img.data;
      if (img.data.startsWith('data:')) {
        pureBase64 = img.data.split(',')[1];
      }
      return {
        id: img.id,
        data: pureBase64,  // Base64 string
        name: img.name
      };
    });
    
    const requestBody = {
      question: question,
      image_data: imageDataArray, // Array of base64 images
      country: country,
      conversation_history: conversationHistory
    };
    
    console.log('📤 Image request payload with', imageDataArray.length, 'images, total size:', JSON.stringify(requestBody).length, 'bytes');
    
    $.ajax({
      url: '/wp-json/chat2find/v1/image',
      method: 'POST',
      contentType: 'application/json',
      data: JSON.stringify(requestBody),
      success: function(response) {
        console.log('✅ Image analysis successful');
      },
      error: function(xhr, status, error) {
        console.error('❌ Image analysis error:', error);
      }
    });
}

Backend WordPress PHP Code

class API_Handler {
public function handle_image_request(WP_REST_Request $request) {
        try {
            error_log('🎯 Image endpoint reached'); // This never fires for large images
            
            $params = $request->get_params();
            $question = sanitize_text_field($params['question'] ?? '');
            $image_data = $params['image_data'] ?? [];
            $country = sanitize_text_field($params['country'] ?? '');
            $conversation_history = $params['conversation_history'] ?? [];
            
            if (empty($question)) {
                return new WP_Error('invalid_input', 'Question is required', array('status' => 400));
            }
            
            if (empty($image_data) || !is_array($image_data)) {
                return new WP_Error('invalid_input', 'Image data array is required', array('status' => 400));
            }
            
            // Validate each image data
            foreach ($image_data as $img) {
                $img_data = is_array($img) ? ($img['data'] ?? '') : $img;
                if (!preg_match('/^[a-zA-Z0-9+\/]+={0,2}$/', $img_data)) {
                    return new WP_Error('invalid_input', 'Invalid image data format', array('status' => 400));
                }
            }
            
            // Limit to maximum 3 images
            if (count($image_data) > 3) {
                return new WP_Error('invalid_input', 'Maximum 3 images allowed', array('status' => 400));
            }
            
            // External API call
            $api_endpoint = get_option('chat2find_api_endpoint', 'https://example.com/api/');
            $image_url = rtrim($api_endpoint, '/') . '/image';
            
            $response = $this->make_api_call($image_url, [
                'question' => $question,
                'image_data' => $image_data,
                'country' => $country,
                'conversation_history' => $conversation_history
            ], false);
            
            if (is_wp_error($response)) {
                error_log('Chat2Find Image API Error: ' . $response->get_error_message());
                return new WP_Error('api_error', 'Image analysis service unavailable', array('status' => 503));
            }
            
            $response_data = json_decode($response, true);
            return new WP_REST_Response($response_data, 200);
            
        } catch (Exception $e) {
            error_log('Chat2Find Image Exception: ' . $e->getMessage());
            return new WP_Error('internal_error', 'Internal server error', array('status' => 500));
        }
    }
    
    public function register_routes() {
        register_rest_route('chat2find/v1', '/image', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_image_request'),
            'permission_callback' => array($this, 'check_permission')
        ));
    }
    
    public function check_permission() {
        return true;
    }

Debugging Attempts

WordPress Debug Logging

// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

Observations

Small images (~100 kb each): works

Large images (~3MB each): Request size ~12-15MB, never reaches backend

Network tab: Shows request being sent but no response received

No server errors in Apache/WordPress logs

No PHP errors even with debugging enabled

Question

What could be silently blocking large JSON requests before they reach WordPress? How do I fix this?

13
  • 2
    Is there a specific reason you're encoding the image as base64 rather than sending as a standard multipart request? base64 encoding enlarges the size of the payload compared to just sending the original binary data. Also because you're not sending binary files in the normal way then upload_max_filesize becomes irrelevant. Commented Oct 21 at 9:52
  • 1
    Small images (~100 kb each): works Large images (~3MB each)...there's a big gap in between those two numbers. Have you worked out the minimum size threshold after which it starts to fail? Is 3MB the minimum size to cause that, or will it fail with anything smaller? Commented Oct 21 at 9:53
  • 1
    Maybe the request gets firewall'ed away, before it reaches your WP. Or even your apache. Maybe there's an nginx with different limits as proxy before the apache. I doubt that anyone without server access will be able to pin-point this from the outside. Commented Oct 21 at 10:11
  • 2
    So there is probably a much lower payload limit in place somewhere earlier in your stack - e.g. client proxy, firewall, gateway, reverse proxy or any other similar infrastructure could potentially interrupt things. I don't know how complex your environment is in terms of that kind of thing. Try doing some network tracing to see how far the request gets once it leaves the browser. Commented Oct 21 at 10:37
  • 2
    Your request is timing out possibly with a reverse proxy like nginx. I don't recommend just increasing the size or time limits as it makes your website a lot more hackable. Instead use a chunked uploader - this will give you paralel chunk uploading faster and without needing to increase limits. Commented Oct 24 at 5:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.