End of refactor

* Simplified storage
* various bugfixes
This commit is contained in:
Phyks 2013-10-11 14:00:00 +01:00
parent de94f7312d
commit 5171fded3f
4 changed files with 32 additions and 24 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
config.php
data

View File

@ -1,7 +1,7 @@
<?php
// The file to which we should store the data
define('DATA_FILE', 'data');
// The base URL with which you will access the script. Keep the trailing slash.
define('BASE_URL', 'http://your.domain.tld/');
// The base URL with which you will access the script. No trailing slash.
define('BASE_URL', 'http://localhost/tinyURL');
// Max number of URLs to keep
define('MAX_SAVED_URLS', 100);

View File

@ -1,5 +1,6 @@
<?php
require('config.php');
if (is_readable(DATA_FILE))
{
$data = unserialize(gzinflate(file_get_contents(DATA_FILE)));
@ -51,15 +52,11 @@ if (count($_GET) != 1) {
// Else, we redirect the visitor to the right URL
else {
// We get the shortened url
// TODO
$get = each($_GET);
$short = $get['key'];
$url = BASE_URL;
foreach($data as $array) {
if ($array['short'] == $short) {
$url = $array['url'];
break;
}
if (array_key_exists($short, $data)) {
$url = $data[$short]['url'];
}
// $url is now index.php if no element was found, the right url if found
header('location:'.$url);

View File

@ -1,16 +1,15 @@
<?php
require('config.php');
// Add a new line to $data
function add($that) {
global $data;
if (count($data) >= MAX_SAVED_URLS)
{
// Delete the first element
array_shift($data);
function sort_array(&$array, $key, $order=SORT_DESC) {
$sort_keys = array();
foreach ($array as $key2 => $entry) {
$sort_keys[$key2] = $entry[$key];
}
// Add that to the array
array_push($data, $that);
return $data;
return array_multisort($sort_keys, $order, $array);
}
if(empty($_POST['url'])) {
@ -18,7 +17,7 @@ if(empty($_POST['url'])) {
}
else {
if (is_readable(DATA_FILE)) {
$data = unserialize(gzinflate(file_get_contents(DATA_DIR.ASSOC_NAME)));
$data = unserialize(gzinflate(file_get_contents(DATA_FILE)));
}
else {
$data = array();
@ -29,7 +28,7 @@ else {
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Shorten me !<title>
<title>Shorten me !</title>
<link rel="stylesheet" media="screen" type="text/css" href="design.css" />
</head>
<body>
@ -44,12 +43,22 @@ else {
if (isset($_POST['url']) && $_POST['url'] != "") {
$url = htmlspecialchars($_POST['url']);
$array = array("url"=>$url, "short"=>$short);
// Add the association at the end of $data array
$data = add($array);
if (count($data) >= MAX_SAVED_URLS)
{
// Delete the first element
sort_array($data, 'timestamp');
array_shift($data);
}
// Store short link in the data array
$data[$short] = array('timestamp'=>time(), 'url'=>$url);
// Save it in the file
file_put_contents(DATA_FILE, gzdeflate(serialize($data)));
// Echoes the result
$new_url = $BASE_URL.'/?'.$short;
$new_url = BASE_URL.'/?'.$short;
?>
<p>Your shorten URL:<br/>
<strong><a href="<?php echo $new_url ?>"><?php echo $new_url; ?></a></strong>