-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.php
More file actions
94 lines (75 loc) · 2.61 KB
/
server.php
File metadata and controls
94 lines (75 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
class FileStorageKeyExistsException extends Exception {}
class FileStorageKeyDoesNotExistException extends Exception {}
class FileStorageErrorReadingFile extends Exception {}
class FileStorageErrorWritingFile extends Exception {}
class FileStorageErrorDeletingFile extends Exception {}
class FileStorage {
protected $dirpath;
public function __construct($dirpath) {
$this->dirpath = rtrim($dirpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
public function generateKey() {
do {
$key = md5(uniqid(null, true));
} while ($this->has($key));
return $key;
}
public function keyToFilepath($key) {
return $this->dirpath . $key;
}
public function has($key) {
$filepath = $this->keyToFilepath($key);
return file_exists($filepath);
}
public function get($key) {
$filepath = $this->keyToFilepath($key);
if (!file_exists($filepath)) {
throw new FileStorageKeyDoesNotExistException('Key does not exist.');
}
$value = file_get_contents($filepath);
if ($value === false) {
throw new FileStorageErrorReadingFile('Error when reading a file.');
}
return $value;
}
public function set($key, $value) {
$filepath = $this->keyToFilepath($key);
if (file_exists($filepath)) {
throw new FileStorageKeyExistsException('Key already exists.');
}
$bytes = file_put_contents($filepath, (string)$value);
if ($bytes === false) {
throw new FileStorageErrorWritingFile('Error when writing to a file.');
}
return $this;
}
public function clear($key) {
$filepath = $this->keyToFilepath($key);
if (!file_exists($filepath)) {
throw new FileStorageKeyDoesNotExistException('Key does not exist.');
}
$status = unlink($filepath);
if ($status === false) {
throw new FileStorageErrorDeletingFile('Error when deleting a file.');
}
return $this;
}
}
$storage = new FileStorage(__DIR__ . '/storage');
if (array_key_exists('action', $_POST)) {
switch ($_POST['action']) {
case 'has':
$returned = array('has' => $storage->has($_POST['key']));
break;
case 'get':
$returned = array('value' => json_decode($storage->get($_POST['key'])));
break;
case 'set':
$key = $storage->generateKey();
$storage->set($key, $_POST['value']);
$returned = array('key' => $key);
break;
}
}
echo json_encode($returned);