]>
Commit | Line | Data |
---|---|---|
451314eb V |
1 | <?php |
2 | /** | |
3 | * GET an HTTP URL to retrieve its content | |
4 | * | |
5 | * @param string $url URL to get (http://...) | |
6 | * @param int $timeout network timeout (in seconds) | |
7 | * @param int $maxBytes maximum downloaded bytes (default: 4 MiB) | |
8 | * | |
9 | * @return array HTTP response headers, downloaded content | |
10 | * | |
11 | * Output format: | |
12 | * [0] = associative array containing HTTP response headers | |
13 | * [1] = URL content (downloaded data) | |
14 | * | |
15 | * Example: | |
16 | * list($headers, $data) = get_http_url('http://sebauvage.net/'); | |
17 | * if (strpos($headers[0], '200 OK') !== false) { | |
18 | * echo 'Data type: '.htmlspecialchars($headers['Content-Type']); | |
19 | * } else { | |
20 | * echo 'There was an error: '.htmlspecialchars($headers[0]); | |
21 | * } | |
22 | * | |
23 | * @see http://php.net/manual/en/function.file-get-contents.php | |
24 | * @see http://php.net/manual/en/function.stream-context-create.php | |
25 | * @see http://php.net/manual/en/function.get-headers.php | |
26 | */ | |
27 | function get_http_url($url, $timeout = 30, $maxBytes = 4194304) | |
28 | { | |
29 | $options = array( | |
30 | 'http' => array( | |
31 | 'method' => 'GET', | |
32 | 'timeout' => $timeout, | |
33 | 'user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0)' | |
34 | .' Gecko/20100101 Firefox/23.0' | |
35 | ) | |
36 | ); | |
37 | ||
38 | $context = stream_context_create($options); | |
39 | ||
40 | try { | |
41 | // TODO: catch Exception in calling code (thumbnailer) | |
42 | $content = file_get_contents($url, false, $context, -1, $maxBytes); | |
43 | } catch (Exception $exc) { | |
44 | return array(array(0 => 'HTTP Error'), $exc->getMessage()); | |
45 | } | |
46 | ||
47 | if (!$content) { | |
48 | return array(array(0 => 'HTTP Error'), ''); | |
49 | } | |
50 | ||
51 | return array(get_headers($url, 1), $content); | |
52 | } |