connect_errno) { header("500 Internal Server Error"); die($SQL['Handle']->connect_errno." ".$SQL['Handle']->connect_error); } } { // Prepare a few statements. $STATEMENTS = array(); $STATEMENTS["LookUp"] = << $v) { $STATEMENTS[$k] = $SQL['Handle']->prepare($v); } } function insert_lookup($url) { global $STATEMENTS; global $SQL; $STATEMENTS['Insert']->bind_param('s', $url); if (!$STATEMENTS['Insert']->execute()) { throw new Exception("".$SQL['Handle']->errno." ".$SQL['Handle']->error); } else if (!$STATEMENTS['Insert']->get_result()) { throw new Exception("".$SQL['Handle']->errno." ".$SQL['Handle']->error); } } function increment_lookup($url) { global $STATEMENTS; global $SQL; $STATEMENTS['Increment']->bind_param('s', $url); if (!$STATEMENTS['Increment']->execute()) { throw new Exception("".$SQL['Handle']->errno." ".$SQL['Handle']->error); } } function redirect_lookup($url) { global $STATEMENTS; global $SQL; $STATEMENTS['LookUp']->bind_param('s', $url); if (!$STATEMENTS['LookUp']->execute()) { throw new Exception("".$SQL['Handle']->errno." ".$SQL['Handle']->error); } $output = null; $res = $STATEMENTS['LookUp']->get_result(); if ($res->num_rows == 0) { insert_lookup($url); } else { while($obj = $res->fetch_object()) { if ($obj->target != null) { $output = $obj->target; increment_lookup($url); break; } } } $res->close(); return $output; } try { // Try and redirect user according to the full provided URI $url = urldecode($_SERVER['REQUEST_URI']); $url_parts = parse_url($url); $location = null; // Try and identify a redirect by the full URI. $location = redirect_lookup($url); if (!($location != null)) { // Try and identify a redirect by the path. $location = redirect_lookup($url_parts["path"]); } if ($location != null) { header("Location: ".$location, true, 307); die(); } // In all other cases, just redirect to 404. header("Location: https://www.xaymar.com/404.html"); } catch(Exception $e) { header("Retry-After: 30", true, 503); echo($e); } die();