aboutsummaryrefslogtreecommitdiffhomepage
path: root/application
diff options
context:
space:
mode:
authorVirtualTam <virtualtam@flibidi.net>2015-09-06 20:32:01 +0200
committerVirtualTam <virtualtam@flibidi.net>2015-09-06 20:32:01 +0200
commit0a813cfd7cdf3c81faba8568bf6e2e667aae6f13 (patch)
treefddc1a6d7a92728d0dfdcbb676f113a09325b1c2 /application
parentf5d6b19b73cd026cb1d937aab16d48b43e412c77 (diff)
parent451314eb48c7d922264adc6eada8a0273b12344c (diff)
downloadShaarli-0a813cfd7cdf3c81faba8568bf6e2e667aae6f13.tar.gz
Shaarli-0a813cfd7cdf3c81faba8568bf6e2e667aae6f13.tar.zst
Shaarli-0a813cfd7cdf3c81faba8568bf6e2e667aae6f13.zip
Merge pull request #334 from virtualtam/refactor/http-utils
HTTP: move utils to a proper file, add tests
Diffstat (limited to 'application')
-rw-r--r--application/HttpUtils.php52
1 files changed, 52 insertions, 0 deletions
diff --git a/application/HttpUtils.php b/application/HttpUtils.php
new file mode 100644
index 00000000..175333ae
--- /dev/null
+++ b/application/HttpUtils.php
@@ -0,0 +1,52 @@
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 */
27function 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}