PHP Doku:: Decode chunked-encoded data - function.http-chunked-decode.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige DiensteHTTPHTTP Funktionenhttp_chunked_decode

Ein Service von Reinhard Neidl - Webprogrammierung.

HTTP Funktionen

<<http_cache_last_modified

http_deflate>>

http_chunked_decode

(PECL pecl_http >= 0.1.0)

http_chunked_decodeDecode chunked-encoded data

Beschreibung

string http_chunked_decode ( string $encoded )

Decodes a string which is HTTP-chunked encoded.

Parameter-Liste

encoded

chunked encoded string

Rückgabewerte

Returns the decoded string on successIm Fehlerfall wird FALSE zurückgegeben..

Beispiele

Beispiel #1 A http_chunked_decode() example

<?php
$string 
"".
    
"05\r\n".
    
"this \r\n".
    
"07\r\n".
    
"string \r\n".
    
"12\r\n".
    
"is chunked encoded\r\n".
    
"01\n\r\n".
    
"00";
echo 
http_chunked_decode($string);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

this string is chunked encoded


Ein BenutzerBeitrag:
- Beiträge aktualisieren...
Marques Johansson
23.03.2009 17:48
Here's a PHP implementation for those less interested in installing a pecl module.  It's a bit naive (doesn't handle multiple byte encodings), but it works.  I'm also including my is_hex() implementation at no additional cost.

<?php
if (!function_exists('http-chunked-decode')) {
   
/**
     * dechunk an http 'transfer-encoding: chunked' message
     *
     * @param string $chunk the encoded message
     * @return string the decoded message.  If $chunk wasn't encoded properly it will be returned unmodified.
     */
   
function http_chunked_decode($chunk) {
       
$pos = 0;
       
$len = strlen($chunk);
       
$dechunk = null;

        while((
$pos < $len)
            && (
$chunkLenHex = substr($chunk,$pos, ($newlineAt = strpos($chunk,"\n",$pos+1))-$pos)))
        {
            if (!
is_hex($chunkLenHex)) {
               
trigger_error('Value is not properly chunk encoded', E_USER_WARNING);
                return
$chunk;
            }

           
$pos = $newlineAt + 1;
           
$chunkLen = hexdec(rtrim($chunkLenHex,"\r\n"));
           
$dechunk .= substr($chunk, $pos, $chunkLen);
           
$pos = strpos($chunk, "\n", $pos + $chunkLen) + 1;
        }
        return
$dechunk;
    }
}

   
/**
     * determine if a string can represent a number in hexadecimal
     *
     * @param string $hex
     * @return boolean true if the string is a hex, otherwise false
     */
   
function is_hex($hex) {
       
// regex is for weenies
       
$hex = strtolower(trim(ltrim($hex,"0")));
        if (empty(
$hex)) { $hex = 0; };
       
$dec = hexdec($hex);
        return (
$hex == dechex($dec));
    }
?>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)