php上传文件的5种方式
作者:zccst
一、普通文件上传方式
关于上次文件,之前已经会的有两种方式,具体如下:
1,使用原生态的php上次文件。
(1)前端代码
(2)php代码(upload_file.php)
<?php if ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/pjpeg"))&& ($_FILES["file"]["size"] < 20000)){ if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; }else { echo "Upload: " . $_FILES["file"]["name"] . "<br>"; echo "Type: " . $_FILES["file"]["type"] . "<br>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>"; if (file_exists("upload/" . $_FILES["file"]["name"])){ echo $_FILES["file"]["name"] . " already exists. "; }else{ move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } }else { echo "Invalid file"; } ?>
2,使用yii框架的CUpload。
参见1:http://zccst.iteye.com/blog/1114948
参见2:http://zccst.iteye.com/blog/1271104
但是,两者面临的相同问题是提交后刷新页面。即非异步上次方式。
二、异步文件上传方式(3种方式)
现在需要异步上传方式,经过同学的帮助和查资料,得知php异步上传文件的有两种实现方式。
1,使用插件(如,jqueryupload)。
2,使用iframe上传,无需额外插件。
根据目前需求:尽量少使用插件。于是采用后者,即使用iframe异步上传文件
具体稍后补充
(1)前端html
function startUpload() { var spanObj = document.getElementById("info"); spanObj.innerHTML = " 开始上传"; document.getElementById("upForm").sumbit(); } //回调 function stopUpload(responseText){ var spanObj = document.getElementById("info"); spanObj.innerHTML = "上传成功"; spanObj.innerHTML = responseText; }
(2)服务器端代码
$file = $_FILES['myfile']; $fileName = uploadFile($file); //$result = readFromFile("../upload/" . $fileName); echo "<script type="text/javascript">window.top.window.stopUpload('{$fileName}')</script>"; function uploadFile($file) { // 上传路径 $destinationPath = "../upload/"; if (!file_exists($destinationPath)){ mkdir($destinationPath , 0777); } //重命名 $fileName = date('YmdHis') . '_' . iconv('utf-8' , 'gb2312' , basename($file['name'])); if (move_uploaded_file($file['tmp_name'], $destinationPath . $fileName)) { return iconv('gb2312' , 'utf-8' , $fileName); } return ''; }
//代码注释 /* 1,关于basename方法 $path = "/testweb/home.php"; //显示带有文件扩展名的文件名 echo basename($path); //显示不带有文件扩展名的文件名 echo basename($path,".php"); 2,关于iconv iconv('gb2312' , 'utf-8' , $fileName);//将$fileName从gb2312转为utf-8格式。 注:该函数需要开启php.ini里面的php_iconv.dll 3,关于$_FILES['myfile'] $_FILES相当于一个二维数组,而$_FILES['myfile']相当于一个一维数组。所以可以 $f = $_FILES['myfile']; echo $f['name']; 如果直接访问该$_FILES['myfile'],则会报Undefined index: myfile。此时加上 if(!isset($_FILES['myfile'])){ die('上传文件不存在!'); } */
3,使用Yii+iframe方式
参见:http://zccst.iteye.com/blog/1271091
附:在网上查到的相关资料如下
http://www.cnblogs.com/spemoon/archive/2011/01/07/1930221.html
http://wenku.baidu.com/view/80522df6ba0d4a7302763abb.html
http://www.jb51.net/article/28427.htm
http://apps.hi.baidu.com/share/detail/20419052

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


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

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
