view urlredirect.php.txt @ 17:b9c27bad2d9a

Updated version for SQLite3 database.
author Matti Hamalainen <ccr@tnsp.org>
date Mon, 05 Sep 2011 16:21:09 +0300
parents 916cffa4f3a1
children 3cf438db908a
line wrap: on
line source

<?
// =====================================================
// URLLog PHP-script for redirecting ShortURLs
// (C) Copyright 2006 Tecnic Software productions (TNSP)
// =====================================================
// SQLite3 database file path and name
$dbFilename = "urllog.sqlite";

// =====================================================
// Helper functions
$idStr = "ABCDEFGHIJKLNMOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

function myerr($str = "") {
	header("Status: 404 Not Found");
	echo "404 Not Found - ".$str;
	exit;
}

// Check arguments
if (isset($_GET["u"]))
	$urlStr = $_GET["u"];
else
	myerr("No ID given.");

// Calculate urlID
$urlLen = strlen($urlStr);
if ($urlLen < 1) myerr("Invalid ID length.");

for ($urlID = 0, $i = 0; $i < $urlLen; $i++) {
	$urlID *= strlen($idStr);

	$n = strpos($idStr, $urlStr[$i]);
	if ($n !== FALSE) {
		$urlID += $n;
	} else
		myerr("Invalid ID.");
}

// Find the URL
try {
  $db = new PDO("sqlite:".$dbFilename);
}
catch (PDOException $e) {
  myerr("Could not connect to URL database: ".$e->getMessage().".");
}

foreach ($db->query("SELECT url FROM urls WHERE id=".$urlID) as $row) {
  header("Location: ".$row["url"]);
  exit;
}

$db = null;
// Output result
myerr("No such ID in database.");
?>