-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsave.php
executable file
·85 lines (70 loc) · 2.31 KB
/
save.php
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
<?php
function fail($code = 1, $msg = 'error', $data = '', $json = false) {
header('Content-type', 'application/json');
echo json_encode(array('code' => $code, 'msg' => $msg, 'data' => $data));
exit;
}
function save() {
// 输入参数校验
$key = isset($_POST['key']) ? urlencode($_POST['key']) : '';
$data = isset($_POST['data']) ? ($_POST['data']) : '';
$overwrite = isset($_POST['overwrite']) ? ($_POST['overwrite']) : '';
if (!$key || !$data) {
fail(1, 'error', '参数不能为空');
}
if (!json_decode($data, true)) {
fail(1, 'error', '存档数据格式不正确');
}
$db_username = SAE_MYSQL_USER;
$db_password = SAE_MYSQL_PASS;
$db_host = SAE_MYSQL_HOST_M;
$db_port = SAE_MYSQL_PORT;
$db_name = SAE_MYSQL_DB;
$dsn = "mysql:host={$db_host};port={$db_port};dbname={$db_name}";
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$save_result = false;
try {
$db = new PDO($dsn, $db_username, $db_password, $options);
if (!$db) {
fail(1, 'fail', '无法存档[1]');
}
$sql = 'SELECT `key` FROM `record` WHERE `key` = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($key));
$found = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($found) {
if ($overwrite == "false") {
header('Content-type', 'application/json');
echo json_encode(array('code' => 2,'msg' => 'repeated'));
exit;
}
$sql = 'UPDATE `record` SET `data` = ? WHERE `key` = ?';
$stmt = $db->prepare($sql);
$ret = $stmt->execute(array($data, $key));
if ($ret) {
$save_result = true;
}
}
else {
$sql = 'INSERT INTO `record`(`key`,`data`) VALUES(?, ?)';
$stmt = $db->prepare($sql);
$ret = $stmt->execute(array($key, $data));
if ($ret) {
$save_result = true;
}
}
}
catch (Exception $e) {
fail(-2, 'fail', '无法存档。');
}
if ($save_result) {
header('Content-type', 'application/json');
echo json_encode(array('code' => 1, 'msg' => 'success'));
}
else {
fail(-1, 'fail', '存档写入失败。');
}
}
save();