0

We want to create some kind of api where the json formatted results are generated using .php files.

The web folder looks like

api
├── .htaccess
└── foo
    ├── bar.php
    └── baz.php

Where bar.php and baz.php are php files generating json-formatted replies on the queries.

Such files (bar.php) look like:

<?php
include_once("../../utils.php");

$id = $_GET['id'];

echo json_encode(some_function($id));
?>

Of course one should specify a header header("Content-type: application/json");. We however want to set the .htaccess to do this, such that one never forgets to set the content-type, that if additional headers are required, we can modify this easily, etc. We don't want to write header(...) in every file.

.htaccess look like:

#All php files return JSON formatted text.
AddType application/json json php

But the generated result has still mime-type: text/html.

What can cause this?

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555

1 Answers1

2

PHP has some values including default_mimetype. When the Apache server generates the .php page, it first sets the application/json mime-type, but when the PHP engine starts, the header is modified back to text/html. You can set this by adding an additional rule to .htaccess:

#All php files return JSON formatted text.
AddType application/json json php
php_value default_mimetype application/json
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555