Skip to content

Instantly share code, notes, and snippets.

@obihann
Created April 1, 2014 17:24
Show Gist options
  • Save obihann/9918818 to your computer and use it in GitHub Desktop.
Save obihann/9918818 to your computer and use it in GitHub Desktop.
Basic PHP script to assist the start of an API. Provides session validation and error logging.
<?php
// Start a new session
session_start();
// Configure error levels
error_reporting(E_ERROR);
ini_set('display_errors', 1);
// Empty response object
$output = (object) response;
// Path to err log
$errorLogs = "/var/www/logs/error.log";
// Obtain IP of remote client
$requestIP = $_SERVER['REMOTE_ADDR'];
// Create error message
$logError = sprintf("\n\n%s - 'function_name' Error (%s) \nerror_string", time(), $requestIP);
// Define salt for session
define("SESSION_SALT", "l3q8MLwY=08p`[A0B|8a`MfFS:#+9njoZss(0=LOc1T&]CASNGGcQQ=G;)mts0Us");
// Generate session key
$sessionKey = hash("sha512", SESSION_SALT . session_id());
// Load session and key
$userSession = $_REQUEST["session"];
$userSessionKey = $_REQUEST["session_key"];
// Check if the session ID provided is valid
if($userSession == session_id() && $userSessionKey == $sessionKey) {
// Do whatever the script is supposed to do here
} else {
// Set JSON response to error and include a message
$output->error = "auth";
$output->response = sprintf("Your IP (%s) is not authorized on this server.", $requestIP);
// Generate a detailed error for the logs
$logError = sprintf("\n\n%s - Auth Error (%s) \nExpected Session: %s \nProvided Session: %s \nExpected Key: %s \nProvided key: %s", time(), $requestIP, $userSession, session_id(), $userSessionKey, $sessionKey);
// Log the error to the file
error_log($logError, 3, $errorLogs);
}
// Encode data, and send it to the user
echo json_encode($output);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment