Add podcast proxy support for Martin
[noxon-gateway.git] / www / proxy.php
1 <?php
2 /**
3  * PHP proxy script that proxies the URL given in the "url" parameter.
4  *
5  * Sends all incoming headers, and also returns all remote headers.
6  * Streams the response, so that large responses should work fine.
7  *
8  * @author Christian Weiske <cweiske@cweiske.de>
9  */
10 require_once __DIR__ . '/../data/config.php';
11 if (!isset($enablePodcastProxy) || $enablePodcastProxy == false) {
12     header('HTTP/1.0 403 Forbidden');
13     echo "Proxying is not enabled in config.php\n";
14     exit(1);
15 }
16
17 if (!isset($_GET['url']) || $_GET['url'] == '') {
18     header('HTTP/1.0 400 Bad Request');
19     echo "url parameter missing\n";
20     exit(1);
21 }
22 if (substr($_GET['url'], 0, 7) != 'http://'
23     && substr($_GET['url'], 0, 8) != 'https://'
24 ) {
25     header('HTTP/1.0 400 Bad Request');
26     echo "Only http and https URLs supported\n";
27     exit(1);
28 }
29
30 $url = $_GET['url'];
31
32 //send original http headers
33 $headers = [];
34 foreach (apache_request_headers() as $name => $value) {
35     if (strtolower($name) == 'host') {
36         continue;
37     }
38     $headers[] = $name . ': ' . $value;
39 }
40 $context = stream_context_create(
41     ['http' => ['header' => $headers, 'ignore_errors' => true]]
42 );
43
44 $fp = fopen($url, 'r', false, $context);
45 if (!$fp) {
46     header('HTTP/1.0 400 Bad Request');
47     echo "Error fetching URL\n";
48     exit(1);
49 }
50
51 //send original headers
52 if (is_array($http_response_header)) {
53     foreach ($http_response_header as $header) {
54         header($header);
55     }
56 }
57
58 //stream the data in 1kiB blocks
59 while(!feof($fp)) {
60     echo fread($fp, 1024);
61     flush();
62 }
63 fclose($fp);
64 ?>