Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP将文本文件一分为二?_Php_Text - Fatal编程技术网

使用PHP将文本文件一分为二?

使用PHP将文本文件一分为二?,php,text,Php,Text,我想取一个文本文件,把它一分为二,把一半放在一个文件里,然后把剩下的一半放在下一个文件里。如何做到这一点 例如:split.php?n=file.txt 这样就可以完成工作,而无需在内存中一次性读取整个文件或其中的一半: 这样就可以完成工作,而无需在内存中一次性读取整个文件或其中的一半: 我可以使用任何一个,我只需要将文件分成两半。如果文件很小,只需使用$file=filegetcontents。然后只需将$variable拆分一半,并使用putfilecontents两次将它们写入disk.u

我想取一个文本文件,把它一分为二,把一半放在一个文件里,然后把剩下的一半放在下一个文件里。如何做到这一点

例如:split.php?n=file.txt

这样就可以完成工作,而无需在内存中一次性读取整个文件或其中的一半:

这样就可以完成工作,而无需在内存中一次性读取整个文件或其中的一半:


我可以使用任何一个,我只需要将文件分成两半。如果文件很小,只需使用$file=filegetcontents。然后只需将$variable拆分一半,并使用putfilecontents两次将它们写入disk.unix-ish主机?为什么不使用exec'split…'?在任何情况下,请小心使用exec或其他方法将$\u GET变量的值直接作为文件名包含在路径字符串中。应该对它进行消毒,这样它就不会被劫持。我可以使用任何一种方法,我只需要对半分割。如果文件很小,只需使用$file=filegetcontents。然后只需将$variable拆分一半,并使用putfilecontents两次将它们写入disk.unix-ish主机?为什么不使用exec'split…'?在任何情况下,请小心使用exec或其他方法将$\u GET变量的值直接作为文件名包含在路径字符串中。它应该经过消毒,以免被劫持。
$file = $_GET['n'];

$i = 1;
$fp = fopen("./server/php/files/".$file,'a+');
$fs = filesize("./server/php/files/".$file);
$lengthhalf = $fs / 2;
while(! feof($fp)) {
    $contents = fread($fp,$lengthhalf);
    file_put_contents('./server/php/files/[2]'.$file,$contents);
    $i++;
}
function split_in_halves($file, $half1, $half2) {
    $size = filesize($file);
    $fd = fopen($file, 'rb');

    stream_copy_to_stream($fd, fopen($half1, 'wb'), $size/2);
    stream_copy_to_stream($fd, fopen($half2, 'wb'));
}
split_in_halves('foo', '[1]foo', '[2]foo');