-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubmit.php
82 lines (74 loc) · 2.22 KB
/
submit.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
<?php
// Enlai Li 261068637
function encrypt($string, $password)
{
$encryption_method = 'aes-256-cbc';
$iv_length = openssl_cipher_iv_length($encryption_method);
$iv = random_bytes($iv_length);
$key = hash('sha256', $password, true);
$ciphertext = openssl_encrypt($string, $encryption_method, $key, OPENSSL_RAW_DATA, $iv);
// encode with base64 for storage
return base64_encode($iv . $ciphertext);
}
// db info
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
try {
$mysqli = new mysqli($servername, $username, $password);
if ($mysqli->connect_error) {
throw new Exception($mysqli->connect_error);
}
// create database
$mysqli->query("CREATE DATABASE IF NOT EXISTS $dbname");
// create table
$mysqli->select_db($dbname);
$mysqli->query("
CREATE TABLE IF NOT EXISTS user_content (
number int NOT NULL AUTO_INCREMENT,
id VARCHAR(255) NOT NULL UNIQUE,
content TEXT NOT NULL,
password BOOLEAN NOT NULL,
visits INT NOT NULL DEFAULT 0,
date DATE NOT NULL DEFAULT CURDATE(),
PRIMARY KEY (number)
);
");
// get inputs
$content = $_POST['content'];
$password = $_POST['password'];
// encrypt content with aes if password is provided
if ($password) {
$content_db = encrypt($content, $password);
$password_db = true;
}
// content stays plaintext if no password
else {
$content_db = $content;
$password_db = false;
}
// generate unique id that doesn't exist in the db
$id = null;
do {
$id = bin2hex(random_bytes(6));
$result = $mysqli->execute_query(
"SELECT COUNT(*) as count FROM user_content
WHERE id = ?",
[$id]
);
$count = $result->fetch_assoc()["count"];
} while ($count > 0);
// insert content
$mysqli->execute_query(
"INSERT INTO user_content (id, content, password) VALUES (?, ?, ?)",
[$id, $content_db, $password_db]
);
// redirect to unique page
header("Location: pastes/$id");
exit();
} catch (Exception $e) {
echo $e->getMessage();
} finally {
$mysqli->close();
}