Skip to content

Instantly share code, notes, and snippets.

@RodionGork
Created January 13, 2015 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RodionGork/c60bfd18aeea98df96bd to your computer and use it in GitHub Desktop.
Save RodionGork/c60bfd18aeea98df96bd to your computer and use it in GitHub Desktop.
Very basic web-application in PHP, allowing to store and retrieve info with the help of json file
<?php
function loadData() {
$file = file_get_contents('data.json');
if ($file === false) {
$file = '[]';
}
$data = json_decode($file);
return empty($data) ? array() : $data;
}
function saveData($data) {
file_put_contents('data.json', json_encode($data));
}
function compareRecords($a, $b) {
return ($a->t < $b->t) ? -1 : (($a->t > $b->t) ? 1 : 0);
}
function addRecord(&$data, $time, $name) {
global $error;
$time = trim($time);
$name = trim($name);
if (!preg_match('/^\d\d\:\d\d$/', $time)) {
$error = 'Time format should be ##:##';
return;
}
if (strlen($name) < 4) {
$error = 'Name is too short';
return;
}
$rec = new stdClass();
$rec->name = $name;
$rec->time = date('Y-m-d') . " $time";
$data[] = $rec;
saveData($data);
}
$curTime = time();
$data = loadData();
if (isset($_POST['time']) && isset($_POST['name'])) {
$time = $_POST['time'];
$name = $_POST['name'];
addRecord($data, $time, $name);
}
$dataNew = array();
foreach ($data as $rec) {
$rec->t = strtotime("{$rec->time}:00 GMT+3");
if ($rec->t < $curTime) {
continue;
}
$s = explode(' ', $rec->time);
$rec->showTime = $s[1];
$dataNew[] = $rec;
}
$data = $dataNew;
usort($data, "compareRecords");
$curTime = date('H:i', $curTime + 3 * 3600);
require 'template.html';
<!doctype html>
<html>
<head>
<title>HitchHiking in DA</title>
<style>
.striped tr:nth-child(odd) {background: #def}
.centered {text-align: center}
</style>
</head>
<body style="font-family:Arial">
<div style="text-align:center;width:1000px;margin:0px auto;">
<?php if (isset($error)) : ?>
<div style="background:pink;color:blue;"><?= $error ?></div>
<?php endif; ?>
<h1>Hello, HitchHiker!</h1>
<form action="./" method="post">
<div>Leave your name and time of departure from office</div><br/>
<label>Time: <input type="text" name="time" size="6" placeholder="18:10" class="centered"/></label>
&nbsp;&nbsp;&nbsp;
<label>Name: <input type="text" name="name" placeholder="John Doe" class="centered"/></label>
&nbsp;&nbsp;&nbsp;
<input type="submit" value="Add me!"/>
</form>
<br/>
<hr style="color:#888;width:60%"/>
<p>Current time: <?= $curTime ?></p>
<table class="striped" style="width:300px;margin:0px auto;">
<tr><th>Time</th><th>Name</th></tr>
<?php foreach ($data as $rec) : ?>
<tr>
<td><?= $rec->showTime ?></td>
<td><?= $rec->name ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment