Backend code for login and XSRF prevention

<?php
$logged_in = session_check();

$token = null;
if(isset($_POST['token'])) $token = $_POST['token'];
else if(isset($_GET['token'])) $token = $_GET['token'];

function auth_check() {
  global $token, $server_secret;
  if(!$token || $_COOKIE['token'] != $token) {
    echo "Token mismatch";
    exit;
  }
  if(!$_COOKIE['auth'] || $_COOKIE['auth'] != sha1($server_secret.$_COOKIE['id'])) {
    echo "Auth mismatch";
    exit;
  }
}

function session_check() {
  global $server_secret;
  if($_COOKIE['auth'] && $_COOKIE['id'] && $_COOKIE['auth'] == 
     sha1($server_secret.$_COOKIE['id'])) {
    SetCookie('token', sha1($auth.rand()));
    return 1;
  }
  return 0;
}
?>