Reputation: 1730
I have built a php script that can sometimes have the server returns a 403 error message (forbidden access) because of the length and content of the data sent through the $_POST method. This 403 error message is returned because of some mod_secure rules that filtrate the data sent on the server.
Is it possible to have PHP handle this 403 error message? For example, I would to catch the server status when I run my script and then display an error message when the server returns the 403 status code. Is that even possible to do this in PHP?
In other words, without making a redirection, I would just like to display in the current page a custom message if the server returns a 403 status code when the PHP script itself is executed.
thanks for your help
Upvotes: 1
Views: 8032
Reputation: 2594
So I have three possible solutions for you.
Check for URL errors and make sure the actual web page is specified. Its common reason for a web site to return the 403 Forbidden error, when the URL is pointing to a directory instead of a web page. Which can be done using HttpRequest Class in PHP. You can use http_get to perform GET request. You can also Test URL here.
<?php
$response = http_get("URL", array("timeout"=>1), $info);
print_r($info);
?>
Output:
array (
'effective_url' => 'URL',
'response_code' => 403,
.
and so on
)
What is important for you is response_code with which you can play further.
Use of curl.
function http_response($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if(!$head)
{
return FALSE;
}
return $httpCode;
}
$errorcode = http_response("URL"); //if success 200 otherwise different
If you're sure the page you're trying to reach is correct, 403 Forbidden error message may be a mistake. Then you can only do two things either contact webmaster or use your own customize redirection. To do that add following line in .htaccess file and handle that error in forbidden.php
ErrorDocument 403 /forbidden.php
Upvotes: 0
Reputation: 35572
It would be to set up a custom error document for 403 errors in Apache, and point this at a script to handle the error. Refer to the ErrorDocument documentation on how to do this, but it would be something along these lines:
ErrorDocument 403 /custom_403_handler.php
Upvotes: 1