-
Notifications
You must be signed in to change notification settings - Fork 1
/
image_proxy.php
88 lines (71 loc) · 2.09 KB
/
image_proxy.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
<?php
$url = isset($argv) ? $argv[1] : $_GET['url'];
$error_code = 200;
function get_lc_headers($url) {
global $error_code;
$ret = array();
$headers = get_headers($url, true);
$error_code = intval(substr($headers[0], 9, 3));
foreach ($headers as $key => $value) {
$ret[strtolower($key)] = $value;
}
return $ret;
}
function try_header($headers, $x) {
$lcx = strtolower($x);
if (isset($headers[$lcx])) {
header("$x: " . $headers[$lcx]);
}
}
$headers = get_lc_headers($url);
if ($error_code == 200) {
$contentType = preg_replace('#;.*$#', '', $headers['content-type']);
if ($contentType == 'text/html') {
$site = file_get_contents($url);
// Parse and find image... First check preview.
// <meta property="og:image" content="THIS"
// <meta name="twitter:image" content="THIS"
if (preg_match('#<meta\s+name="twitter:image"\s+content="([^"]+)"#i', $site, $matches)) {
$url = $matches[1];
$headers = get_lc_headers($url);
}
elseif (preg_match('#<meta\s+property="og:image"\s+content="([^"]+)"#i', $site, $matches)) {
$url = $matches[1];
$headers = get_lc_headers($url);
}
// Else handle specific instances...
else {
$error_code = 424;
}
}
}
if ($error_code == 200) {
$contentType = preg_replace('#;.*$#', '', $headers['content-type']);
$parts = explode('/', $contentType);
if ($parts[0] == 'image') {
// If this allows the client to download it, just redirect.
if (isset($headers['access-control-allow-origin']) && $headers['access-control-allow-origin'] == '*') {
header("Location: $url");
}
// Otherwise, only proxy if it's small enough...
elseif (isset($headers['content-length']) && $headers['content-length'] < 1024 * 1024) {
$image = file_get_contents($url);
http_response_code(200);
try_header($headers, 'Last-Modified');
try_header($headers, 'Content-Type');
try_header($headers, 'Content-Length');
echo $image;
}
else {
// Meant for client payload but w/e.
$error_code = 413;
}
}
else {
// Meant for client payload but w/e.
$error_code = 415;
}
}
if ($error_code != 200) {
http_response_code($error_code);
}