So I want to write a REST API in PHP for JSON for consumption on the iPhone, but also a lot of websites and devices. I have the below code, when accessed via a GET statemen
Not entirely such what your goal is but here are 3-4 solutions that might work:
This is probaly the most conventional way of getting clean URIs for your API. If you want the user part of user.json to be dynamic, you can use mod_rewrite (again assuming Apache) to rewrite your URLs to a php handler script. If you are going the conventional RESTful style URL route, you will probably want to use this anyway to achieve clean /
separated URLs.
# For grabbing all users
RewriteEngine on
RewriteRule ^users\.json rest.php [L]
# For grabbing one particular user
RewriteEngine on
RewriteRule ^([a-z0-9]+)\.json rest.php?user=$1 [L]
Where rest.php is your PHP handler script.
If you don't want to use mod_rewrite, you can also do something like
example.com/rest.php/users.json
example.com/rest.php/user-id.json
or even
example.com/rest.php/user-id
example.com/rest.php/user/user-id
Where rest.php is your PHP handler script. You can grab the user-id
from the URL (or URI if we're talking RESTful terms) using the $_SERVER
global with $_SERVER['REQUEST_URI']
.
I believe you want to add the Content-Disposition header...
This will force the file to be downloaded as user.json. This usually isn't the behavior expected for a REST API, but from the way your question was worded, I figured I'd throw it out there.
Assuming you're running an Apache server, you can also just use AddHandler
directive to make .json
extension files be treated like they are php.
AddHandler application/x-httpd-php .json
Warning: Other plain .json files will be treated as PHP so you'd probably want to set this in a .htaccess file in the directory with the PHP script. This would work fine for this one URI but not ideal if you were exposing many URIs