-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.php
288 lines (260 loc) · 7.83 KB
/
index.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
<?php
/*
*
* The first part handles application logic.
*
*/
include("config.php");
session_start();
$server = $_SERVER['SERVER_ADDR'];
// Simulate latency
sleep($latency);
if (isset($_POST['username']))
{
// This is a login request
process_login($_POST['username']);
}
if (isset($_GET['logout']))
{
// This is a logout request
process_logout();
}
if (isset($_FILES["fileToUpload"]) && isset($_SESSION['username']))
{
// Check file type before processing
$file_temp = "/tmp/".basename($_FILES["fileToUpload"]["name"]);
$file_size = $_FILES["fileToUpload"]["size"];
error_log("Handling $file_temp with $file_size bytes");
$file_type = strtolower(pathinfo($file_temp, PATHINFO_EXTENSION));
if(($file_type != "jpg") && ($file_type != "png") && ($file_type != "jpeg") && ($file_type != "gif") )
{
// Not an image file, ignore the upload request
}
else
{
$username = $_SESSION['username'];
// This is an image upload request, save the file first
if ($storage_option == "hd")
{
// In config.php, we specify the storage option as "hd"
$key = save_upload_to_hd($_FILES["fileToUpload"], $hd_folder);
add_upload_info($db, $username, $key);
}
else if ($storage_option == "s3")
{
// In config.php, we specify the storage option as "S3"
$key = save_upload_to_s3($s3_client, $_FILES["fileToUpload"], $s3_bucket, $s3_prefix);
add_upload_info($db, $username, $key);
}
if ($enable_cache)
{
// Delete the cached record, the user will query the database to get an updated version
if ($cache_type == "memcached")
{
$cache->delete($cache_key);
}
else if ($cache_type == "redis")
{
$cache->del($cache_key);
}
}
}
}
function process_login($username)
{
// Simply write username to session data
$_SESSION['username'] = $username;
}
function process_logout()
{
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies"))
{
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
}
// Finally, destroy the session.
session_destroy();
}
function save_upload_to_hd($uploadedFile, $folder)
{
// Rename the target file with a UUID
$ext = pathinfo($uploadedFile["name"], PATHINFO_EXTENSION);
$uuid = uniqid();
$key = $uuid.".".$ext;
// Copy the upload file to the target file
$tgtFile = $folder."/".$key;
move_uploaded_file($uploadedFile["tmp_name"], $tgtFile);
return $key;
}
function save_upload_to_s3($s3_client, $uploadedFile, $s3_bucket, $s3_prefix)
{
try
{
// Rename the target file with a UUID
$ext = pathinfo($uploadedFile["name"], PATHINFO_EXTENSION);
$uuid = uniqid();
if (empty($s3_prefix))
{
$key = $uuid.".".$ext;
}
else
{
$key = $s3_prefix."/".$uuid.".".$ext;
}
// Upload the uploaded file to S3 bucket
$s3_client->putObject(array(
'Bucket' => $s3_bucket,
'Key' => $key,
'SourceFile' => $uploadedFile["tmp_name"]
));
error_log("Uploaded to S3 as s3://$s3_bucket/$key.");
} catch (S3Exception $e)
{
echo "There was an error uploading the file to S3.\n";
return false;
}
return $key;
}
function add_upload_info($db, $username, $filename)
{
// Add a new record to the upload_images table
$sql = "INSERT INTO upload_images (username, filename) VALUES (?, ?)";
$statement = $db->prepare($sql);
$statement->execute(array($username, $filename));
}
function retrieve_recent_uploads($db, $count)
{
// Print a message so that the user knows these records come from the DB.
echo "Getting latest $count records from database.<br>";
error_log("Getting latest $count records from database.");
// Geting the latest records from the upload_images table
$sql = "SELECT * FROM upload_images ORDER BY timeline DESC LIMIT $count";
$statement = $db->prepare($sql);
$statement->execute();
$images = $statement->fetchAll(PDO::FETCH_ASSOC);
return $images;
}
function db_rows_2_html($images, $storage_option, $hd_folder, $s3_client, $s3_bucket, $enable_cf, $cf_baseurl)
{
$html = "\n";
if ($enable_cf == true)
{
// Images can be either on S3 or HD
foreach ($images as $image)
{
$filename = $image["filename"];
$url = $cf_baseurl.$filename;
$html = $html."<img src='$url' width=200px height=150px>\n";
}
}
else if ($storage_option == "hd")
{
// Images are on hard disk
foreach ($images as $image)
{
$filename = $image["filename"];
$url = $hd_folder."/".$filename;
$html = $html."<img src='$url' width=200px height=150px>\n";
}
}
else if ($storage_option == "s3")
{
// Images are on S3
foreach ($images as $image)
{
$filename = $image["filename"];
//Create S3 presigned URL
$cmd = $s3_client->getCommand('GetObject',
['Bucket' => $s3_bucket, 'Key' => $filename]);
$req = $s3_client->createPresignedRequest($cmd, '+600 minutes');
$url = (string) $req->getUri();
$html = $html. "<img src='$url' width=200px height=150px>\n";
}
}
return $html;
}
?>
<?php
/*
*
* The second part handles user interface.
*
*/
echo "<html>\n";
echo "<head>\n";
echo "<META http-equiv='Content-Type' content='text/html; charset=UTF-8'>\n";
echo "<title>Scalable Web Application</title>\n";
echo "<script src='demo.js'></script>\n";
echo "</head>\n";
echo "<body>\n";
if (isset($_SESSION['username']))
{
$username = $_SESSION['username'];
// This section is shown when user is login
echo "<table width=100% border=0>";
echo "<tr>";
echo "<td><H1>$server</H1></td>";
echo "<td align='right'>";
echo "$username<br>";
echo "<a href='index.php?logout=yes'>Logout</a>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "<HR>";
echo "In this demo, we assume that you are uploading images files with file extensions such as JPG, JPEG, GIF, PNG.<br> <br>";
echo "<form action='index.php' method='post' enctype='multipart/form-data'>";
echo "<input type='file' id='fileToUpload' name='fileToUpload' id='fileToUpload' onchange='check_file_type();'>";
echo "<input type='submit' value='Upload Image' id='submit_button' name='submit_button' disabled>";
echo "</form>";
}
else
{
// This section is shown when user is not login
echo "<table width=100% border=0>\n";
echo "<tr>\n";
echo "<td><H1>$server</H1></td>\n";
echo "<td align='right'>\n";
echo "<form action='index.php' method='post'>";
echo "Enter Your Name: <br>";
echo "<input type='text' id='username' name ='username' size=20><br>";
echo "<input type='submit' value='login'/>";
echo "</form>\n";
echo "</td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "<HR>\n";
}
// Get the most recent N images
if ($enable_cache)
{
error_log("Cache enabled, try to obtain the cached version.");
// Attemp to get the cached records for the front page
$images_html = $cache->get($cache_key);
if (!$images_html)
{
// If there is no such cached record, get it from the database
$images = retrieve_recent_uploads($db, 10, $storage_option);
// Convert the records into HTML
$images_html = db_rows_2_html($images, $storage_option, $hd_folder, $s3_client, $s3_bucket, $enable_cf, $cf_baseurl);
// Then put the HTML into cache
$cache->set($cache_key, $images_html);
}
}
else
{
// This statement get the last 10 records from the database
$images = retrieve_recent_uploads($db, 10, $storage_option);
$images_html = db_rows_2_html($images, $storage_option, $hd_folder, $s3_client, $s3_bucket, $enable_cf, $cf_baseurl);
}
// Display the images
echo $images_html;
$session_id = session_id();
echo "<hr>";
echo "Session ID: ".$session_id;
echo "\n</body>";
echo "\n</html>";
?>