2012-09-29 77 views
0

我有一种“开始”的解决方案。 我写了这个功能(很抱歉的间距):(再次,抱歉:))拆分和组合文件

<?php 
set_time_limit(0); 

// Just to get the remote filesize 

function checkFilesize($url, $user = "", $pw = ""){ 

ob_start(); 

$ch = curl_init($url); 

curl_setopt($ch, CURLOPT_HEADER, 1); 

curl_setopt($ch, CURLOPT_NOBODY, 1); 

if(!empty($user) && !empty($pw)){ 

    $headers = array('Authorization: Basic ' . base64_encode("$user:$pw")); 

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 

} 

$ok = curl_exec($ch); 

curl_close($ch); 

$head = ob_get_contents(); 

ob_end_clean(); 

$regex = '/Content-Length:\s([0-9].+?)\s/'; 

$count = preg_match($regex, $head, $matches); 

return isset($matches[1]) ? $matches[1] : "unknown"; 

} 

// Split filesize to threads 

function fileCutter($filesize,$threads){ 

$calc = round($filesize/count($threads)); 

$count = 0; 

foreach($threads as $thread){ 

    $rounds[$count] = $calc; 

    $count++; 

} 

$count = 0; 

foreach($rounds as $round){ 

    $set = $count + 1; 

    if($count == 0){ 

    $from = 0; 

    } else { 

    $from = ($round * $count); 

    } 

    $cal = ($round * $set); 

    $final[$count] = array('from'=>$from,'to'=>$cal); 

    $count++; 

} 

// Correct the "Rounded" result 

$end = end($final); 

$differance = $filesize - $end['to']; 

if (strpos($differance,'-') !== false) {} else {$add = '+';} 

$end_result = ($end['to'].$add.$differance); 

$value=eval("return ($end_result);"); 

$end_id = end(array_keys($final)); 

$final[$end_id]['to'] = $value; 

// Return the complete array with the corrected result 

return $final; 

} 

$threads = array(
0=>'test', 
1=>'test', 
2=>'test', 
3=>'test', 
4=>'test', 
5=>'test', 
); 

$file = 'http://www.example.com/file.zip'; 

$filesize = checkFilesize($file); 

$cuts = fileCutter($filesize,$threads); 

print_r($cuts); 

?> 

它提供了 “方向” 将文件分割特定字节。 我试着做一些像这样:

foreach($cuts as $cut){ 
$start = $cut['from']; 
$finish = $cut['to']; 
$f = fopen($file, "rb"); 
fseek($f, $start, SEEK_SET); 
while(!(ftell($f) > $finish)){ 
    $data = fgetc($f); 
} 
fclose($f); 

但它要一个死循环。 问题是什么?或者,PHP中是否有另一种解决方案来分割和合并文件?

+1

看看http://stackoverflow.com/a/12407208/1226894它可以按行或大小拆分...你也应该看看http://stackoverflow.com/a/10271542/1226894 – Baba

回答

3

不用手动读取文件,并逐个字节你可以只使用file_get_contents()与根据参数$offset$maxlen

//        $incp $ctx $offset $maxlen 
$data = file_get_contents($fn, FALSE, NULL, $start, $finish-$start); 

那会做的追求和切割为您服务。

+0

太棒了!谢谢! –