Perhaps this question belongs on Stack Overflow or another site instead, in which case please tell me and don't just downvote; I will gladly move it.
Anyway, I'm just learning the very basics of server management and I was playing around with my own small, private MySQL server on my laptop when I happened upon something I hadn't expected. When I sent an AJAX request to a PHP page using the jQuery $.ajax() method, I was continuing to get the response code of "200" even though I called the function http_response_code(500);
in my PHP code. I couldn't figure out why this was happening until I realized that I was using echo
statements to return data to the Javascript page, and by moving the http_response_code(500);
function to above all of the echo
statements, it would set the HTTP response code correctly.
I understand this is correct functionality, I am just wondering why this is the case? Why must the HTTP response code be set before using echo functions? What's happening in the underlying protocols? My guess is that it has something to do with echo
forcing the script to return data when it is called, but then why do scripts like the following:
echo "thing one";
echo "thing two";
http_response_code(500);
echo "thing three";
...still echo "thing three" just fine but don't change the response code?
I'm not having a "problem" per se, I'm just here to learn! Thanks!
When you print anything on the body, headers must be already sent. That's if you e.g.
echo()
something or even if there's a space before the<?php
. A web server simply can't output anything before it has sent the headers, as that's the form of a HTTP response, causing any output to send the headers, too.If you try to use e.g.
header()
that sends a header, you could get aWarning: Cannot modify header information - headers already sent by
.Because
http_response_code()
does not send HTTP headers, but only prepares the header list to be sent later on, it won't trigger this error. While usingheaders_sent()
in anif
condition can prevent these errors withheader()
, it could also be useful for debugging issues when usinghttp_response_code()
.