You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PHP设置JSON类型HTTP头时出现双Content-Type响应问题

Fixing Duplicate Content-Type Headers in PHP Responses

Hey there, let's break down why you're seeing two conflicting Content-Type headers in Postman and how to fix this issue.

The Root Cause

Most likely, PHP is automatically sending a default text/html; charset=UTF-8 header before your custom application/json header gets set. This happens when:

  • There's accidental output (like spaces, newlines, or stray HTML) before your <?php opening tag.
  • Your PHP file has a UTF-8 BOM (byte order mark) added by your editor—this invisible character counts as output and triggers header sending.
  • You’re using echo, print, or similar functions anywhere before calling header().

Once headers are sent (even automatically by PHP), you can’t replace them—you can only add new ones. That’s why you end up with duplicate headers. The true parameter in your second header call only works if the header hasn’t been sent yet.

Quick Fixes to Try

  1. Eliminate Accidental Pre-Output
    Double-check your PHP file:

    • No spaces, newlines, or other characters before the <?php tag.
    • Save your file without a UTF-8 BOM (most editors let you set this in save options, like VS Code’s "UTF-8 without BOM").
    • Ensure no echo, print, or var_dump calls run before your header() lines.
  2. Explicitly Remove Existing Content-Type Headers
    Add header_remove('Content-Type'); before setting your custom header to wipe out any auto-generated headers:

    <?php
    // Wipe out any existing Content-Type header first
    header_remove('Content-Type');
    // Set the 400 status code
    header("HTTP/1.1 400 BAD REQUEST");
    // Set the correct Content-Type (note no space before the colon!)
    header("Content-Type: application/json;charset=utf-8", true);
    
    // Output your JSON response
    echo json_encode(['error' => 'Invalid request parameters']);
    ?>
    
  3. Debug Early Output with headers_sent()
    Use PHP’s built-in function to pinpoint where headers are being sent prematurely:

    <?php
    if (headers_sent($file, $line)) {
        die("Oops! Headers were already sent in $file on line $line");
    }
    // Rest of your header code here
    ?>
    

    This will tell you exactly which file and line is causing the early output.

  4. Fix Header Syntax
    While not the main issue, the space before the colon in Content-Type : is non-standard. Remove it to match HTTP header conventions (Content-Type:) and avoid any potential parsing quirks.

Why This Works

By removing pre-existing Content-Type headers before setting your own, you ensure only your application/json header is sent. Fixing pre-output prevents PHP from auto-sending the default text/html header in the first place.

内容的提问来源于stack exchange,提问作者Pandat Arun

火山引擎 最新活动