Getting File Size of > 2 GB Files in PHP Without External Programs
The default methods of determining file size, such as filesize(), stat(), and fseek(), fail to accurately capture the size of files exceeding 2 GB. However, a viable solution exists within PHP 32-bit platforms utilizing the open-source project, Big File Tools.
Big File Tools: A Comprehensive Solution
Big File Tools encompasses a range of techniques specifically designed to manipulate files greater than 2 GB. This platform-independent library offers a robust approach, initially attempting to leverage system-specific shell commands. In scenarios where shell commands are unavailable, it employs Windows COM or resorts to filesize().
Implementing the Solution
The following PHP code showcases how to implement the Big File Tools solution:
<code class="php">/* * This software may be modified and distributed under the terms * of the MIT license. */ function filesize64($file) { static $iswin; if (!isset($iswin)) { $iswin = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'); } static $exec_works; if (!isset($exec_works)) { $exec_works = (function_exists('exec') && !ini_get('safe_mode') && @exec('echo EXEC') == 'EXEC'); } // try a shell command if ($exec_works) { $cmd = ($iswin) ? "for %F in (\"$file\") do @echo %~zF" : "stat -c%s \"$file\""; @exec($cmd, $output); if (is_array($output) && ctype_digit($size = trim(implode("\n", $output)))) { return $size; } } // try the Windows COM interface if ($iswin && class_exists("COM")) { try { $fsobj = new COM('Scripting.FileSystemObject'); $f = $fsobj->GetFile( realpath($file) ); $size = $f->Size; } catch (Exception $e) { $size = null; } if (ctype_digit($size)) { return $size; } } // if all else fails return filesize($file); }</code>
This implementation ensures accurate file size determination for files exceeding 2 GB without the need for external programs.
The above is the detailed content of How to Determine File Size of Files Larger Than 2 GB in PHP Without Using External Tools?. For more information, please follow other related articles on the PHP Chinese website!