#!/usr/bin/php restoredfile */ //Set the following to True to enable debugging info. define('VERBOSE',False); //Reference: http://www.faqs.org/rfcs/rfc2616.html //Copied from a comment at http://br.php.net/install.unix.commandline if (version_compare(phpversion(),'4.3.0','<')) { define('STDIN',fopen("php://stdin","rb")); define('STDOUT',fopen("php://stout","wb")); define('STDERR',fopen("php://sterr","w")); register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STOUT); fclose(STERR); return true;' ) ); fputs(STDERR,"You use a very old PHP version, UPDATE NOW! (to avoid problems later)\n"); } function warn($s) { fputs(STDERR,$s."\n"); } //$filename = ""; //$fp = fopen ($filename, "r"); define('STDIN',fopen("php://stdin","rb")); $fp = STDIN; $out = STDOUT; $totalsize = 0; $totalchunks = 0; $line = fgets($fp); //Checks if the file starts with a chunk, or if we should first skip HTTP headers if( sscanf($line,"%x",$chunksize)!=1 ) { //Skip HTTP headers do{ $line=fgets($fp); }while($line!="\r\n" && !feof($fp)); //Found a blank line (or EOF) if(feof($fp)) { warn("EOF found while skipping headers. Maybe invalid input file?"); exit(1); } //Since this is a blank line, I need to read the next line, and it will be a chunk $line=fgets($fp); } //Chunk-reading loop while(!feof($fp)) { if(sscanf($line,"%x",$chunksize)!=1) { warn("Invalid format when reading chunk ".($totalchunks+1)); exit(2); } if($chunksize==0) { warn("Happy end. $totalsize octets read/written, from $totalchunks chunks."); } $totalsize += $chunksize; $totalchunks++; // For some reason, PHP limits the maximum number of bytes read from a file. So, I need to make a loop. $remaining = $chunksize; while($remaining>0) { $data=fread($fp, $remaining); if(VERBOSE) { warn("chunk #$totalchunks: read ".strlen($data)." octets of $chunksize ($remaining remaining)."); } // if(strlen($data)!=$chunksize) // { // warn("Read error at chunk $totalchunks: read ".strlen($data)." octets, expected $chunksize octets. Continuing anyway..."); // } fwrite($out,$data); $remaining-=strlen($data); } //Removes the CRLF at end of each chunk-data $line=fgets($fp); if($line!="\r\n") { warn("Found extra characters after chunk-data $totalchunks (with expected size $chunksize). Only CRLF was expected. Continuing anyway..."); } //Gets next chunk-size $line=fgets($fp); } //fclose($fp); ?>