Sietse Sietse - 7 months ago 44
PHP Question

Content-Type in ErrorDocument

I am building a small framework for my API's since they are quite specific, but I have a problem with the Content-Type when I received data for an ErrorDocument. Currently, I have the following .htaccess:

<IfModule mod_headers.c>
Header set Content-Type "text/plain"
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
RewriteRule ^([a-z]+)(/[A-Za-z0-9-\._\/]*)?$ $1.php [QSA,L]

ErrorDocument 404 "API_NOT_FOUND"
</IfModule>


What I want to achieve is the error 404 with a different Content-Type. Either text/plain or application/json would be fine, but none of those works. So probably I can't set the Content-Type header in the .htaccess like I want to. I also tried the ErrorDocument as a file, but since the path to the directory is dynamic, I can't use an error document without the path hardcoded like:

ErrorDocument 404 /api/index.php?error=404


The .htaccess is inside the api directory, but the directory can be renamed. Is there any way I can achieve one of the following things?


  • Set a Content-Type inside the .htaccess so the ErrorDocument doesn't have the text/html with a charset.

  • Set the error document to index.php in the directory the .htaccess is.



If the first one works, would I still be able to override it inside the .php scripts? Some of my calls are JSON, other are XML files.

Answer

Thanks for the answers and sorry to provide the final answer this late. I have found a solution which I think works like it should.

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

RewriteRule ^([A-Za-z0-9_-]+)(/[A-Za-z0-9-\._\/]*)?$ $1.php [QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^([a-z]+) index.php?error=404 [L]
</IfModule>

The error is redirected to the index.php which outputs the right stuff after doing the logging itself, so it is a win-win situation I believe. For the simple explanation, the following lines will be executed in the index.php:

http_response_code(404);
die(json_encode(['error' => ['code' => 'API_SCRIPT_NOT_FOUND', 'number' => 404]]);