This repository was archived by the owner on Dec 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathproxy.php
64 lines (47 loc) · 1.46 KB
/
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
<?php
/* Config */
$upstream_base_url = 'http://127.0.0.1:9000';
$timeout = 5; // seconds
$latency = 0; // simulate latency; seconds
/* Read incoming request */
$request_method = $_SERVER['REQUEST_METHOD'];
$request_uri = $_SERVER['REQUEST_URI'];
$request_headers = getallheaders();
$request_body = file_get_contents('php://input');
/* Simulate latency */
if ($latency) {
sleep($latency);
}
/* Forward request */
$url = $upstream_base_url . $request_uri;
$headers = array();
foreach ($request_headers as $key => $value) {
$headers[] = $key . ': ' . $value;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_method);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
header('HTTP/1.1 502 Bad Gateway');
header('Content-Type: text/plain');
echo 'Upstream host did not respond.';
} else {
$header_length = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response_headers = explode("\n", substr($response, 0, $header_length));
$response_body = substr($response, $header_length);
foreach ($response_headers as $header) {
$header = trim($header);
if ($header) {
header(trim($header));
}
}
echo $response_body;
}
curl_close($ch);