php实现上传进度条的方法:首先向服务器端上传一个文件;然后用PHP将此次文件上传的详细信息存储在session当中;接着用Ajax周期性的请求一个服务器端脚本;最后通过浏览器端的Javascript显示更新进度条即可。

推荐:《PHP视频教程》
实现文件上传进度条基本是依靠JS插件或HTML5的File API来完成,其实PHP配合ajax也能实现此功能。
PHP手册对于session上传进度是这么介绍的:
当 session.upload_progress.enabled INI 选项开启时,PHP 能够在每一个文件上传时监测上传进度。 这个信息对上传请求自身并没有什么帮助,但在文件上传时应用可以发送一个POST请求到终端(例如通过XHR)来检查这个状态
当一个上传在处理中,同时POST一个与INI中设置的session.upload_progress.name同名变量时,上传进度可以在$_SESSION中获得。 当PHP检测到这种POST请求时,它会在$_SESSION中添加一组数据, 索引是 session.upload_progress.prefix 与 session.upload_progress.name连接在一起的值。 通常这些键值可以通过读取INI设置来获得,例如
<?php
$key = ini_get("session.upload_progress.prefix") . ini_get("session.upload-progress.name");
var_dump($_SESSION[$key]);
?>
通过将$_SESSION[$key]["cancel_upload"]设置为TRUE,还可以取消一个正在处理中的文件上传。 当在同一个请求中上传多个文件,它仅会取消当前正在处理的文件上传和未处理的文件上传,但是不会移除那些已经完成的上传。 当一个上传请求被这么取消时,$_FILES中的error将会被设置为 UPLOAD_ERR_EXTENSION。
session.upload_progress.freq 和 session.upload_progress.min_freq INI选项控制了上传进度信息应该多久被重新计算一次。 通过合理设置这两个选项的值,这个功能的开销几乎可以忽略不计。
注意:为了使这个正常工作,web服务器的请求缓冲区需要禁用,否则 PHP可能仅当文件完全上传完成时才能收到文件上传请求。 已知会缓冲这种大请求的程序有Nginx。下面原理介绍:
当浏览器向服务器端上传一个文件时,PHP将会把此次文件上传的详细信息(如上传时间、上传进度等)存储在session当中。然后,随着上传的进行,周期性的更新session中的信息。这样,浏览器端就可以使用Ajax周期性的请求一个服务器端脚本,由该脚本返回session中的进度信息;浏览器端的Javascript即可根据这些信息显示/更新进度条了。
php.ini需配置以下选项
session.upload_progress.enabled = "1" session.upload_progress.cleanup = "1" session.upload_progress.prefix = "upload_progress_" session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS" session.upload_progress.freq = "1%" session.upload_progress.min_freq = "1"
其中enabled控制upload_progress功能的开启与否,默认开启;
cleanup 则设置当文件上传的请求提交完成后,是否清除session的相关信息,默认开启,如果需要调试$_SESSION,则应该设为Off。
prefix 和 name 两项用来设置进度信息在session中存储的变量名/键名。
freq 和 min_freq 两项用来设置服务器端对进度信息的更新频率。合理的设置这两项可以减轻服务器的负担。
在上传文件的表单中,需要为该次上传设置一个标识符,并在接下来的过程中使用该标识符来引用进度信息。
具体的,在上传表单中需要有一个隐藏的input,它的name属性为php.ini中 session.upload_progress.name 的值;它的值为一个由你自己定义的标识符。如下:
代码如下:
<input type="hidden" name="<?php echo ini_get('session.upload_progress.name'); ?>" value="test" />
接到文件上传的表单后,PHP会在$_SESSION变量中新建键,键名是一个将session.upload_progress.prefix的值与上面自定义的标识符连接后得到的字符串,可以这样得到:
代码如下:
$name = ini_get('session.upload_progress.name'); $key = ini_get('session.upload_progress.prefix') . $_POST[$name]; $_SESSION[$key]; // 这里就是此次文件上传的进度信息了
$_SESSION[$key]这个变量的结构是这样的:
array ( 'upload_progress_test' => array ( 'start_time' => 1491494993, // 开始时间 'content_length' => 1410397, // POST请求的总数据长度 'bytes_processed' => 1410397, // 已收到的数据长度 'done' => true, // 请求是否完成 true表示完成,false未完成 'files' => array ( 0 => array ( 'field_name' => 'file1', 'name' => 'test.jpg', 'tmp_name' => 'D:\\wamp\\tmp\\phpE181.tmp', 'error' => 0, 'done' => true, 'start_time' => 1491494993, 'bytes_processed' => 1410096, ), ), ), );
这样,我们就可以使用其中的 content_length 和 bytes_processed 两项来得到进度百分比。
原理介绍完了,下面我们来完整的实现一个基于PHP和Javascript的文件上传进度条。
上传表单index.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>PHP(5.4) Session 上传进度 Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content=""/>
<meta name="description" content=""/>
<meta name="author" content="">
<link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
body{
font-size:1em;
color:#333;
font-family: "宋体", Arial, sans-serif;
}
h1, h2, h3, h4, h5, h6{
font-family: "宋体", Georgia, serif;
color:#000;
line-height:1.8em;
margin:0;
}
h1{ font-size:1.8em; }
#wrap{
margin-top:15px;
margin-bottom:50px;
background:#fff;
border-radius:5px;
box-shadow:inset 0 0 3px #000,
0 0 3px #eee;
}
#header{
border-radius:5px 5px 0 0;
box-shadow:inset 0 0 3px #000;
padding:0 15px;
color:#fff;
background: #333333;
}
#header h1{
color:#fff;
}
#article{
padding:0 15px;
}
#footer{
text-align:center;
border-top:1px solid #ccc;
border-radius:0 0 5px 5px;
}
.progress {
width: 100%;
border: 1px solid #4da8fe;
border-radius: 40px;
height: 20px;
position: relative;
}
.progress .labels {
position: relative;
text-align: center;
}
.progress .bar {
position: absolute;
left: 0;
top: 0;
background: #4D90FE;
height: 20px;
line-height:20px;
border-radius: 40px;
min-width: 20px;
}
.report-file {
display: block;
position: relative;
width: 120px;
height: 28px;
overflow: hidden;
border: 1px solid #428bca;
background: none repeat scroll 0 0 #428bca;
color: #fff;
cursor: pointer;
text-align: center;
float: left;
margin-right:5px;
}
.report-file span {
cursor: pointer;
display: block;
line-height: 28px;
}
.file-prew {
cursor: pointer;
position: absolute;
top: 0;
left:0;
width: 120px;
height: 30px;
font-size: 100px;
opacity: 0;
filter: alpha(opacity=0);
}
.container{
padding-left:0;
padding-right:0;
margin:0 auto;
}
</style>
</head>
<body>
<p id="wrap" class="container">
<p id="header">
<h1 id="Session上传进度-nbsp-Demo">Session上传进度 Demo</h1>
</p>
<p id="article">
<form id="upload-form" action="upload.php" method="POST" enctype="multipart/form-data" style="margin:15px 0"
target="hidden_iframe">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="test"/>
<p class="report-file">
<span>上传文件…</span><input tabindex="3" size="3" name="file1" class="file-prew" type="file" onchange="document.getElementById('textName').value=this.value">
</p>
<input type="text" id="textName" style="height: 28px;border:1px solid #f1f1f1" />
<p>
<input type="submit" class="btn btn-default" value="上传"/>
</p>
</form>
<p id="progress" class="progress" style="margin-bottom:15px;display:none;">
<p class="bar" style="width:0%;"></p>
<p class="labels">0%</p>
</p>
</p> <!-- #article -->
<p id="footer">
<p> </p>
</p>
</p><!-- #wrap -->
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank" style="display:none;"></iframe>
<script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function fetch_progress() {
$.get('progress.php', {'<?php echo ini_get("session.upload_progress.name"); ?>': 'test'}, function (data) {
var progress = parseInt(data);
$('#progress .labels').html(progress + '%');
$('#progress .bar').css('width', progress + '%');
if (progress < 100) {
setTimeout('fetch_progress()', 500);
} else {
$('#progress .labels').html('100%');
}
}, 'html');
}
$('#upload-form').submit(function () {
$('#progress').show();
//图片比较小,看不出进度条加载效果,初始设33%
$('#progress .labels').html('33%');
$('#progress .bar').css('width', '33%');
setTimeout('fetch_progress()', 500);
});
</script>
</body>
</html> 注意表单中的session.upload_progress.name隐藏项,值设置为了test。表单中仅有一个文件上传input,如果需要,你可以添加多个。
这里需要特别注意一下表单的target属性,这里设置指向了一个当前页面中的iframe。这一点很关键,通过设置target属性,让表单提交后的页面显示在iframe中,从而避免当前的页面跳转。因为我们还得在当前页面显示进度条呢。
上传文件upload.php
<?php
/**
* 上传文件
*/
if(is_uploaded_file($_FILES['file1']['tmp_name'])){
//unlink($_FILES['file1']['tmp_name']);
$fileName = 'pic_' . date('YmdHis') . mt_rand(10000,99999);
$ext = substr($_FILES['file1']['name'], strrpos($_FILES['file1']['name'], '.'));
move_uploaded_file($_FILES['file1']['tmp_name'], $fileName . $ext);
}ajax获取上传进度progress.php
<?php
/**
* AJAX获取上传文件进度
*/
session_start();
$i = ini_get('session.upload_progress.name');
//session.upload_progress.name = "PHP_SESSION_UPLOAD_PROGRESS"
$key = ini_get("session.upload_progress.prefix") . $_GET[$i];
//session.upload_progress.prefix = "upload_progress_" . 'test'
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"]; // 已收到的数据长度
$total = $_SESSION[$key]["content_length"]; // POST请求的总数据长度
echo $current < $total ? ceil($current / $total * 100) : 100;
}else{
echo 100;
}注意事项:
1.input标签的位置name为session.upload_progress.name的input标签一定要放在文件input 的前面。
2.通过设置 $_SESSION[$key]['cancel_upload'] = true 可取消当次上传。但仅能取消正在上传的文件和尚未开始的文件。已经上传成功的文件不会被删除。
3.应该通过 setTimeout() 来调用 fetch_progress(),这样可以确保一次请求返回之后才开始下一次请求。如果使用 setInterval() 则不能保证这一点,有可能导致进度条出现'不进反退'。
The above is the detailed content of How to implement upload progress bar in php. For more information, please follow other related articles on the PHP Chinese website!
ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PMThe article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and
PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PMThe article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.
PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PMArticle discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.
PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PMThe article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand
PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PMThe article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur
OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PMThe article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.
PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PMThe article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.
PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PMThe article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor







