Clarity needed on usage of multiple 403 forbidden header() functions at the beginning of the plugin files

The proper way to send a status (when WordPress is not available) is:

http_response_code( 403 );

See the PHP Manual for its definition.

But in Plugin files, this should never be the “default” code on top of a file header. See Worthwhile to restrict direct access of theme files? for a discussion.

In WordPress, use status_header( 403 ) if you need it.


A note on the code you’ve posted:

header( 'Status: 403 Forbidden' );
header( 'HTTP/1.1 403 Forbidden' );

The first line is a “special” treatment for PHP running in CGI mode, the second is using a specific HTTP protocol version without any check. If the connection is over HTTP 2 or 1.1, this makes no sense.

Both are wrong, because the correct way to send the proper status with header() is using the second and the third argument of that function.

So this would work better:

header( 'Status: 403 Forbidden', true, 403 );

The second argument tells PHP to overwrite other headers with the same name, the third is for the real status. The code that you posted is a good counter-example. 🙂

Leave a Comment