aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/HttpUtils.php
diff options
context:
space:
mode:
authorVirtualTam <virtualtam@flibidi.net>2015-09-01 21:45:06 +0200
committerVirtualTam <virtualtam@flibidi.net>2015-09-06 19:30:26 +0200
commit451314eb48c7d922264adc6eada8a0273b12344c (patch)
treefddc1a6d7a92728d0dfdcbb676f113a09325b1c2 /application/HttpUtils.php
parentf5d6b19b73cd026cb1d937aab16d48b43e412c77 (diff)
downloadShaarli-451314eb48c7d922264adc6eada8a0273b12344c.tar.gz
Shaarli-451314eb48c7d922264adc6eada8a0273b12344c.tar.zst
Shaarli-451314eb48c7d922264adc6eada8a0273b12344c.zip
HTTP: move utils to a proper file, add tests
Relates to #333 Modifications: - move HTTP utils to 'application/HttpUtils.php' - simplify logic - replace 'http_parse_headers_shaarli' by built-in 'get_headers()' - remove superfluous '$status' parameter (provided by the HTTP headers) - apply coding conventions - add test coverage (unitary only) Signed-off-by: VirtualTam <virtualtam@flibidi.net>
Diffstat (limited to 'application/HttpUtils.php')
-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}