Skip to content

Instantly share code, notes, and snippets.

@gnh1201
Last active March 25, 2024 09:02
Show Gist options
  • Save gnh1201/0de864199991dcfc9d97e7982862f6e0 to your computer and use it in GitHub Desktop.
Save gnh1201/0de864199991dcfc9d97e7982862f6e0 to your computer and use it in GitHub Desktop.
Super-simple JSON-RPC 2.0 framework for PHP
<?php
// Super-simple JSON-RPC 2.0 framework for PHP
// MIT License
// Namhyeon Go <abuse@catswords.net>
// created: 2024-03-22
// updated: 2024-03-25
function jsonrpc2_encode($method, $params, $id = '') {
$data = array(
"jsonrpc" => "2.0",
"method" => $method,
"params" => $params,
"id" => $id
);
return json_encode($data);
}
function jsonrpc2_result_encode($result, $id = '') {
$data = array(
"jsonrpc" => "2.0",
"result" => $result,
"id" => $id
);
return json_encode($data);
}
function jsonrpc2_error_encode($error, $id = '') {
$data = array(
"jsonrpc" => "2.0",
"error" => $error,
"id" => $id
);
return json_encode($data);
}
// CSRF check
function jsonrpc2_generate_token($key = '_csrf_token') {
if (!isset($_SESSION))
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION[$key] = $token;
return $token;
}
// CSRF check
function jsonrpc2_check_token($token, $key = '_csrf_token') {
if (!isset($_SESSION))
return false;
return !empty($token) && !empty($_SESSION[$key]) && $token == $_SESSION[$key];
}
function jsonrpc2_read_input() {
$context = json_decode(file_get_contents('php://input'), true);
if ($context == NULL && in_array("JSONData", $_POST)) {
$context = json_decode($_POST['JSONData']);
}
return $context;
}
// CSRF check
function jsonrpc2_load_scripts($csrf_key = "_csrf_token") {
return <<<EOF
var $csrf_key = "";
function generate_csrf_token() {
// generate CSRF token
$.post("ajax.html", JSON.stringify({
"jsonrpc": "2.0",
"method": "generate_csrf_token",
"params": {},
"id": ""
}), function(data) {
$csrf_key = data.result.$csrf_key;
}, "json");
}
generate_csrf_token();
function get_csrf_token() {
return $csrf_key;
}
if (typeof $.fn.serializeObject === "undefined") {
$.fn.serializeObject = function () {
var formData = {};
var formArray = this.serializeArray();
for (var i = 0, n = formArray.length; i < n; ++i)
formData[formArray[i].name] = formArray[i].value;
return formData;
};
}
EOF;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment