I am writing a PHP service which will listen for JSON requests (made using jQuery) and will return the JSON responses.
The whole template for such services (there will be 5) I have shortened into this template:
<?php
// set the headers which are accepted
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: origin, content-type, accept, authorization");
//header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD");
header("Access-Control-Allow-Methods: POST");
header('Content-Type: application/json');
// "HTTPS-only " validation
$isSecure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$isSecure = true;
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
$isSecure = true;
}
$REQUEST_PROTOCOL = $isSecure ? 'https' : 'http';
if (!$isSecure) {
$response['status'] = 1;
$response['message'] = 'Connection is not secure';
http_response_code(400);
echo json_encode($response);
exit;
}
// !! for debug only !!
error_reporting(E_ALL);
// get the request data
$postdata = file_get_contents("php://input");
// decode
$request = json_decode($postdata, true);
$response = [];
try {
if (true) {
throw new Exception(); // validation not passed case
}
// proccess request data .. make calculations
// all went successfull case
$response['status'] = 0;
$response['message'] = 'OK';
} catch (Exception $ex) {
$response['status'] = 3;
$response['message'] = 'Exception';
} finally {
if ($response['status'] === 0) {
// set the response code to 200: OK
http_response_code(200);
} else {
http_response_code(400);
}
// output the answer
echo json_encode($response);
}
Here is the approach I am using:
- set the allowed headers
- allow only
HTTPS
based calls (noHTTP
) - decode the input data
- make data validation and analysis
- throw a custom
Exception
if some validation is not passed - in
finally
block echo the accumulatedresponse
variable
I am quite experienced when it comes down to PHP
services so I am looking for an advice - if the above mentioned pattern/template can be improved in any way? Add additional validation?
The basic use cases are: new user registration/login/change password/get data specific to provided object ID, pushing some data to DB etc.