How to force an HTTP error code from PHP

Posted by ljmacphee on August 29, 2008 under how to, php, security |

If something happens in your php script you may want to force an HTTP error, rather than continue or redirect the user to another page. This is very simple to do. Just be sure the first line of output from your script to the browser is

header(’HTTP/1.0 403 Forbidden’);

or

header(’HTTP/1.0 404 Not found’);

Or which ever standard code other than 200 you wish to send.

If you are using the Security Plugin instead of redirecting the attacker to an error page you can send back an HTTP error.

There are two HTML Error pages in the security script, one for blocked ips, one for all else.


// print error page
print “<html>\n”;
print “<head><title>Banned</title></head>\n”;
print “<body>\n”;
print “<h2>Banned: $blacklisted:  $code</h2>\n”;
print “<p>If you believe this to be in error please contact <a href=\”mailto:timestocome@gmail.com\”>timestocome@gmail.com</a>”;
print “</body>\n”;
print “</html>\n”;


What you will do is remove or comment out the error page and in it’s place put:
header(’HTTP/1.0 403 Forbidden’);

No print, no extra quotes - use it just as I have it here.


$code = “Sorry but you are listed on our ip blacklist”;
global $wpdb;
header(’HTTP/1.0 403 Forbidden’);
exit();


Feel free to use any of the standard codes. HTTP/1.1 Error Codes

Add A Comment

You must be logged in to post a comment.