示例#1
0
/**
 * Output a JSON response, terminate script execution.
 *
 * @param mixed $result
 * @param SignatureSecretKey $signingKey Optional - used for API responses.
 */
function json_response($result, $signingKey = null)
{
    if (!\headers_sent()) {
        \header("Content-Type: application/json");
        \header('X-Content-Type-Options: nosniff');
        \header('X-Download-Options: noopen');
        \header('X-Frame-Options: SAMEORIGIN');
        \header('X-XSS-Protection: 1; mode=block');
    }
    if ($signingKey instanceof SignatureSecretKey || $signingKey instanceof SignatureKeyPair) {
        if ($signingKey instanceof SignatureKeyPair) {
            // We don't need the whole keypair.
            $signingKey = $signingKey->getSecretKey();
        }
        $message = \json_encode($result, JSON_PRETTY_PRINT);
        $signature = Crypto::sign($message, $signingKey, true);
        unset($signingKey);
        die(Base64UrlSafe::encode($signature) . "\n" . $message);
    }
    // Otherwise, we're just dumping the message verbatim:
    die(\json_encode($result, JSON_PRETTY_PRINT));
}