Home Backend Development PHP Tutorial The idea of ​​​​making PHP upload files with progress

The idea of ​​​​making PHP upload files with progress

Jun 06, 2018 pm 03:05 PM
php

This article mainly introduces the idea of ​​​​making PHP upload files with progress. Interested friends can refer to it. I hope it will be helpful to everyone.

php Progressive uploading of large files has always been a problem that troubles PHP programmers. Query baidu and Google, and the general methods for uploading with progress are: flash php, socket, apc php, etc. Below I introduce the upload with progress produced by apc php ajax, and post the source code, I hope it will be helpful Useful to everyone.
Alternative PHP Cache (APC) is a free and public optimized code cache for PHP. It is used to provide a free, open and robust framework for caching and optimizing PHP intermediate code.

When using apc, you must first install the apc module.
Step 1: Download php_apc.dll

##Step 2: Make php.ini support apc extension module. Put php_apc.dll into your ext directory, then open php.ini and add:
extension=php_apc.dll apc.rfc1867 = on
apc .max_file_size = 100M
upload_max_filesize = 100M
post_max_size = 100M
//The above parameters can be defined by yourself

The third step : Check whether PHP APC is supported

 if (function_exists('apc_fetch')) {
 echo 'it surpport apc model!';
 } else {
 echo "it's not support apc model!";
 }
 ?>
Copy after login

Let’s get to the point:Principle:Through the APC module, use ajas from Read the upload progress from the cache. For details, see:
index.php

<?php
 $unid=uniqid("");//确定唯一标致,实现多人同时上传
?>
<p class="userinput2">
 <p id="captions">先将你要上传的软件上传服务器,上传时请耐心等候...<span class="style1"><br />
 </span>
 <script type="text/javascript" >
 var xmlHttp;
 var proNum=0;
 var loop=0;
 //初始化xmlHttp
 function createxml(){
 var xmlHttp;
 if(window.XMLHttpRequest){
 xmlHttp=new XMLHttpRequest();
 }else{
 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 return xmlHttp;
 }
 xmlHttp=createxml();
 //ajas操作
 function sendURL() {
 var url="getprogress.php?progress_key=<?php echo $unid;?>";
 xmlHttp.open("GET",url,false);
 if (window.navigator.userAgent.indexOf("Firefox")>=1){
 //如果是firefox3.0
 xmlHttp.send("progress_key=<?php echo $unid;?>");
 if(xmlHttp.status==200) doHttpReadyStateChange();
 
 }else{
 xmlHttp.onreadystatechange = doHttpReadyStateChange;
 xmlHttp.send("progress_key=<?php echo $unid;?>");
 }
 }
 //回调函数
 function doHttpReadyStateChange() {
 if (xmlHttp.readyState== 4){
 proNum=parseInt(xmlHttp.responseText);
 //alert(proNum);
 document.getElementByIdx_x("progressinner").style.width = proNum+"%";
 document.getElementByIdx_x("showNum").innerHTML = proNum+"%";
 if ( proNum < 100){
 setTimeout("sendURL()", 200);
 }else{
 //上传成功后,还不能及时得到信息。还希望高人指点
 document.getElementByIdx_x("progressouter").style.display="none";
 document.getElementByIdx_x("progressinner").style.display="none";
 document.getElementByIdx_x("showNum").style.display="none";
 document.getElementByIdx_x("theframe").style.display="none";
 document.getElementByIdx_x("link2").style.display="block";
 }
 
 }
 }
 function startProgress(){
 document.getElementByIdx_x("progressouter").style.display="block";
 setTimeout("sendURL()", 200);
 }
 function newsofturl(text){
 document.getElementByIdx_x("link2").style.display="block";
 document.getElementByIdx_x("link2").value=text;
 }
 </script>
 <iframe id="theframe" name="theframe" src="softupload.php?id=<?php echo($unid); ?>" style="border: 0; height: 80px; width: 400px; " frameborder="0" scrolling="no" > </iframe>
 <input name="linkdefult" type="hidden" id="linkdefult" value="0" />
 <br />
 <p id="link2" style="display:none;" > <font size=2>上传成功!    文件大小为:
 <input type="text" name="filesize" id="filesize" style="width:50px;"/>
 </font><br>
 <br>
 <font size=2>文件下载地址为:</font><br />
 <input type=text name=&#39;link&#39; id=&#39;link&#39; style=&#39;width:380px;&#39; />
 </p>
 <br/>
 <p id="progressouter" style="width: 500px; height: 20px; border: 1px solid #000000; display:none;">
 <p id="progressinner" style="position: relative; height: 20px; background-color: #333333; width: 0%; "></p>
 </p>
 <p id=&#39;showNum&#39; style="font-size:12px; color:#333333"></p>
 </p>
</p>
Copy after login

softupload.php

<?php
 $id = $_GET[&#39;id&#39;];
?>
<script language="javascript">
//Trim the input text
function Trim(input)
{
 var lre = /^\s*/;
 var rre = /\s*$/;
 input = input.replace(lre, "");
 input = input.replace(rre, "");
 return input;
 }
function CheckForTestFile()
 {
 var file = document.getElementByIdx_x(&#39;Softfile&#39;);
 var fileName=file.value; 
 //Checking for file browsed or not
 if (Trim(fileName) ==&#39;&#39; )
 {
 alert("请为上传选择一个文件!!!");
 file.focus();
 return false;
 }
 //Setting the extension array for diff. type of text files
 var extArray = new Array(".rar", ".zip", ".exe", ".gz"); 
 //getting the file name
 while (fileName.indexOf("\") != -1)
 fileName = fileName.slice(fileName.indexOf("\") + 1);

 //Getting the file extension  
 var ext = fileName.slice(fileName.indexOf(".")).toLowerCase();
 for (var i = 0; i < extArray.length; i++)
 {
 if (extArray[i] == ext)
 {
 window.parent.startProgress(); return true;
 }
 }
 alert("正确的文件格式为" + (extArray.join(" ")) + "\n请选择一个新的 " + "文件提交上传.");
 file.focus();
 return false; 
 } 
</script> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<form enctype="multipart/form-data" id="upload_form" action="target.php" method="POST">
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $id?>"/>
<table width="322" border="0" cellpadding="0" cellspacing="0" id="linkTable">

 <tr>
 <td >1.选择软件<br />

 <input name="Softfile" type="file" id="Softfile" /></td>
 <td ><br />
 <input name="submit" type="submit" onclick="return CheckForTestFile();" value="上传软件"/></td>
 </tr>
 </table>
</form>
Copy after login

target.php

<script language="javascript">
//将上传后的信息返还给父窗口
function chuanzhi(){
parent.document.getElementByIdx_x(&#39;filesize&#39;).value=document.getElementByIdx_x(&#39;size&#39;).value;
parent.document.getElementByIdx_x(&#39;link&#39;).value=document.getElementByIdx_x(&#39;newsoftdir&#39;).value;
parent.document.getElementByIdx_x(&#39;linkdefult&#39;).value=1;
}
</script>
<body onLoad="chuanzhi();">
<?php
//header(&#39;Content-Type:text/html;charset=gb2312&#39;);
define(&#39;SOFTDIR&#39;, "./upload/"); //上传后路径
define(&#39;HTTPSOFTDIR&#39;, "http://www.mysite.com/"); //服务器的路径

//判断上传软件后缀名是否允许
function isSoftExt($extension) {
 $ext = array(&#39;exe&#39;, &#39;rar&#39;, &#39;zip&#39;,&#39;gz&#39;);
 return in_array($extension, $ext) ? true : false;
}
if($_SERVER[&#39;REQUEST_METHOD&#39;]==&#39;POST&#39;){
$errors[&#39;0&#39;] = true;
$errors[&#39;1&#39;] = &#39;请选择上传的软件图片&#39;;
$errors[&#39;2&#39;] = &#39;上传软件图片失败&#39;;
$errors[&#39;3&#39;] = &#39;上传软件图片失败&#39;;
$daytime = date(&#39;Y-m-d-h-m-s&#39;);
$timename=str_replace("-","",$daytime); //取得当天的日期时间


 //检查软件是否是正常上传的
 if(!is_uploaded_file($_FILES[&#39;Softfile&#39;][&#39;tmp_name&#39;])) {
 echo "<script>alert(&#39;非正常上传!&#39;);history.back();</script>";
 exit;
 }
 $extension = pathinfo($_FILES[&#39;Softfile&#39;][&#39;name&#39;], PATHINFO_EXTENSION);
 $filename = $timename."_".$_FILES[&#39;Softfile&#39;][&#39;name&#39;];
 $tmpsize=$_FILES[&#39;Softfile&#39;][&#39;size&#39;];
 $msize=round($tmpsize/1048576 , 2) ."M";
 $ksize=round($tmpsize/1024 ,2). "K";
 $filesize =$tmpsize>1048576?$msize:$ksize;
 //检查软件文件格式
 if(!isSoftExt($extension)) {
 echo "<script>alert(&#39;上传的软件格式有错误!&#39;);history.back();</script>";
 exit;
 } 
 //移动软件
 if(!move_uploaded_file($_FILES[&#39;Softfile&#39;][&#39;tmp_name&#39;], SOFTDIR. $filename)) {
 echo "<script>alert(&#39;移动软件出错!&#39;);history.back();</script>";
 exit;
 }else{
 echo "<font size=2>上传成功!    文件大小为:<input type=text id=&#39;size&#39; value=&#39;$filesize&#39;></font><br>";
 echo "<font size=2>文件下载地址为:</font><input type=text id=&#39;newsoftdir&#39; value=&#39;".HTTPSOFTDIR.$filename."&#39; style=&#39;width=380&#39;>";
 }
}else
echo "请不要直接输入地址!";

?>
Copy after login

getprogress.php

<?php
//上传ajas获取进度页面
session_start();
if(isset($_GET[&#39;progress_key&#39;])) {
 $status = apc_fetch(&#39;upload_&#39;.$_GET[&#39;progress_key&#39;]);
 echo ($status[&#39;current&#39;]/$status[&#39;total&#39;])*100;
}
echo &#39;APC_FILE=&#39;.APC_FILE;
?>
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

PDO transaction processing methods and example analysis in PHP

Solution to the conflict between __autoload and Smarty in PHP Detailed explanation of the method

Solutions and examples of the garbled problem of PHP using PDO to operate the database

The above is the detailed content of The idea of ​​​​making PHP upload files with progress. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles