Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trigger 403 in php so that it shows the ErrorDocument

recently I set up custom-made error documents for my server.

I started with a 404 page and this works like a charm: file not found automatically shows the specified 404.php page. However, with 403 I have some trouble. I set it up the same way, but I only get a blank page. It does not show the 403.php page as set in the .htaccess document. Any ideas?

Here is my code:

.htaccess:

Options -Indexes
ErrorDocument 403 /403.php
ErrorDocument 404 /404.php

php:

<?php 
header("HTTP/1.1 403 Unauthorized");
exit;
?>
like image 786
Kolja Avatar asked Jan 22 '14 15:01

Kolja


2 Answers

The error document defined in the server's config only get's loaded when the server (Apache) encounters a 403 error.

If you force an error through PHP, like send 403 status code, this happens in PHP not in Apache.

So when you already know the site I want to render will fail due to unauthorized, why leave it up to apache what will happen?

<?php 
header("HTTP/1.1 403 Unauthorized");
// either:
header("Location: /403.php");
// or:
include('403.php');
exit;
?>

I started with a 404 page and this works like a charm:

Are you sure?

Do you have a script, sending 404 and get redirected to 404.php? Or did you just open a non-existent URI and got redirected?

like image 199
Daniel W. Avatar answered Oct 15 '22 11:10

Daniel W.


Go to your server's real 403 page. (Go to a forbidden URL on your server, or go to any 403 page you like)

Right-click and select 'view source'. Select all the source and save it to file on your domain like: http://domain.com/403.php

Now go to your real forbidden page (or a forbidden situation in some part of your php) example: http://domain.com/members/my_forbidden_page.php

echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won't work) The code below should be your first line!

<?php header('HTTP/1.0 403 Forbidden');
$contents = file_get_contents('/home/your_account/public_html/domain.com/403.php', TRUE);
exit($contents);

I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.

like image 30
Tarik Avatar answered Oct 15 '22 09:10

Tarik