Ticket #119: temp.php

File temp.php, 2.4 kB (added by dmp, 2 years ago)

Exemple implementation to read Accept-encodings headers

Line 
1
2
3
4 /**
5  * Lecture générique d'un header accept
6  *
7  * @param   string  $string
8  * @return  array   array((string) $type => (int) $preference)
9  * @access  private
10  */
11
12 function __http_read_all_accept($string) {
13     preg_match_all('/([^,;\s]+)(?:;q=([^,]+))*/', $string, $match = array ());
14     $qualities = array_pop($match);
15     $types = array_pop($match);
16     $exit = array();
17     foreach ($types as $key => $type) {
18         $exit[$type] = $qualities[$key] ? $qualities[$key] : 1;
19     }
20     return $exit;
21 }
22
23
24 /**
25  * Retourne un tableau contenant la liste des encodings que nous proposons, qui sont acceptables par le client
26  *
27  * @param   string  $string (header client)
28  * @param   array   $encodings (tableau des encodings que l'on propose)
29  * @return  mixed   false si rien d'acceptable, array((string) $type=>(int)
30  * $preference) sinon. Le tableau éventuel est classé par ordre croissant de
31  * préférence.
32  * @internal   L'identité est (presque) toujours acceptable
33  */
34
35 function __http_read_accept_encoding($string, $encodings) {
36     $exit = false;
37     $accept = __http_read_all_accept($string);
38     // The identity is always acceptable
39     // unless a *; q=0 exists and no explicit identity declaration
40     // and unless identity; q=0 is not defined
41     $exit = array ('identity' => 1);
42     $accept_keys = array_keys($accept);
43     if (count($accept)) {
44         $all_is_defined = in_array('*', $accept_keys);
45         foreach ($encodings as $encoding) {
46         // If an encoding is listed, and has a quality > 0, he is acceptable
47             if (in_array($encoding, $accept_keys)) {
48                 !$accept[$encoding] or $exit[$encoding] = $accept[$encoding];
49             }
50         // Else, if there exists a * encoding with a quality > 0, the encoding not explicitely listed
51         // inherits it
52             elseif ($all_is_defined && $accept['*']) {
53                 $exit[$encoding] = $accept['*'];
54             }
55         }
56         // Treat the identity:
57         // If the identity is defined:
58         if(isset($accept['identity'])){
59             // If q=0, unset it
60             if(!$accept['identity'])
61                 unset($exit['identity']);
62         }
63         // If it's not defined, but *; q=0 is defined, also unset it
64         elseif($all_is_defined && !$accept['*']){
65                 unset($exit['identity']);
66         }
67     }
68
69     !is_array($exit) or asort($exit, SORT_NUMERIC);
70     return $exit;
71 }
72
Download in other formats: Original Format