【问题标题】:How to Read some files parts with php如何使用 php 读取一些文件部分
【发布时间】:2019-10-13 19:49:13
【问题描述】:

我需要在读取文件时获取start、end和md5 hash的值,然后将其插入数据库。它工作得很好 读取整个文件时,值会正确插入到数据库中。

现在假设我有一个大约 883mb 的文件,我想读取最后一个 880mb 而排除第一个 3mb。 p>

我怎样才能做到这一点。(即从剩余的 4mb 到 883mb 读取并将其相应的值插入数据库)

我在这里找到的解决方案只是读取文件的最后 1mb Read part of a file in PHP

这是读取整个文件时的工作代码

   $fragSize = 1 * 1024 * 1024; // chunk 1 mb
       $file = file_get_contents('mydata.zip'); //about 883mb
        $fileSize = strlen($file);
        $numFragments = ceil($fileSize / $fragSize);
        $i = 0;

        while ($i < $numFragments) {
            $chunkSize = $fragSize;
            $start = $i * $fragSize;
            $end = $i * $fragSize + $chunkSize - 1;
            $offset = $i * $fragSize;

            if ($stream = fopen('mydata.zip', 'r')) {

// you have to chunk the files to avoid memory issues
                $data = stream_get_contents($stream, $chunkSize);
                fclose($stream);
            }
          $hash = md5($data);

           // insert start, end and hash value to database

    // pdo connection
    $statement = $db->prepare('INSERT INTO data1
    (start_read,end_read,hash_read)

                              values
    (:start_read,:end_read,:hash_read)');

    $statement->execute(array( 

    ':start_read' => $start,
    ':end_read' => $end,
    ':hash_read' => $hash       
    ));


        $i++;
    }

【问题讨论】:

    标签: php


    【解决方案1】:

    您正在读取数据两次。一个是file_get_contents,另一个是fread。没必要。我猜您希望将第 4 MB、最后一个 MB 以及整个文件的哈希值插入到数据库中。你可以这样做:

    // set filename to a variable
    $filename = "mydata.zip";
    // open the file for reading
    $f = fopen($filename, "r");
    // set the cursor position where the 3rd MB ends
    fseek($f, 3 * 1024 * 1024, SEEK_SET);
    // read 1MB of data
    $first = fread($f, 1024);
    // set the cursor position to the start of last MB
    fseek($f, -1024, SEEK_END);
    // read 1MB of data
    $last = fread($f, 1024);
    // get the hash of the file    
    $hash = md5($file);
    

    【讨论】:

    • 感谢 Taha Paksu 先生的回复。我在您的答案中看到了最后 1 mb 的读数,但我想要的是这个。让我们假设文件是​​ 883mb。然后我昨天首先读取了 3mb 的 mydata.zip,剩下的 880mb,现在我想今天读取剩余的文件,所以我应该从 4mb 开始读取,直到最后一个 883mb。所以我不会重新读取文件,而是继续从我停止的地方读取,这就是为什么我在 while 循环中传递它。然后当它循环时,我将值插入数据库,直到文件完成读取。请您进一步提供帮助
    • 就像我上面所说的,我需要继续插入每个开始、结束和散列的值,因为它循环直到文件完成读取或完成,就像我在 while 循环中所做的那样。感谢等待您的来信
    • 你好@Henrymart,我提供的代码包括让你得到你想要的知识。你想直接复制/粘贴整个工作代码吗?
    猜你喜欢
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多