如何在PHP中获取当前上传的字节?

时间:2012-02-15 02:33:40

标签: php

如何记录并获取从html表单上传到PHP脚本的当前字节?我想稍后将当前进度存储在会话或日志中,以便另一个AJAX脚本可以检索它。这是我当前读取当前字节的代码,但它不起作用。

$file_type = $_FILES['Filedata']['type'];
$file_name = $_FILES['Filedata']['name'];
$file_size = $_FILES['Filedata']['size'];
$file_tmp = $_FILES['Filedata']['tmp_name'];

 $filePointer = fopen($_FILES['Filedata']['tmp_name'], "rb");
 $rr=0;

 if ($filePointer!=false){
 while (!feof($filePointer)){
     $fileData = fread($filePointer, 4096);
     $rr =$rr+strlen($fileData);
     // Process the contents of the uploaded file here...
     $_SESSION['fname']=$rr;
 }

fclose($filePointer);
}

move_uploaded_file ($file_tmp, "files/".$file_name);

2 个答案:

答案 0 :(得分:4)

您不能以这种方式访问​​上传的字节,因为在文件上传之前脚本不会被调用。

您的服务器需要安装APC或类似的pecl包

http://devzone.zend.com/1812/using-apc-with-php/

或者使用HTML5文件api

http://www.matlus.com/html5-file-upload-with-progress/

HTML5更好,因为您不必在php端更改任何内容,只需设置脚本来接收文件,但需要用户的浏览器支持HTML5文件api。

答案 1 :(得分:3)

有一个PECL包:http://pecl.php.net/package/uploadprogress

否则请检查:

您必须在tmp文件夹中找到正确的文件并测量大小。此大小必须显示在每隔几秒钟通过AJAX爬网的页面上。问题是如何匹配正确的会话和文件。但这并非不可能......