search
HomeBackend DevelopmentPHP TutorialPHP---File upload and download, _PHP tutorial

PHP---File upload and download,

Reprinted from http://www.cnblogs.com/lazycat-cz/p/4113037.html

Safety performance---insufficient level ╮(╯_╰)╭

File upload--->It is to upload local files to the server. (HTTP protocol needs to be learned)First, select the uploaded file locally. After uploading to the server, the server needs to do some processing. For this, both the client and the server need to make some settings

(Client) The most basic method of file upload is to POST the file through the form and paste the code first.

<html>
<body>

<form action="upload_file.php" method="post"  enctype="multipart/form-data">
<label <span>for</span>="file">选择文件:</label>
<input type="file" name="uploadFile" id="file" /> <br /><br /><input type="submit" name="submit" value="上传" /> </form> </body> </html>
The enctype attribute of the

tag specifies which content type to use when submitting the form. Use "multipart/form-data" when your form requires binary data, such as file content. The type="file" attribute of the

tag specifies that the input should be processed as a file. For example, when previewing in a browser, you'll see a browse button next to the input box.

(Server) The file uploaded to the server still needs to go through some processing. In php, $_POST saves the data passed by post, and the relevant information of the uploaded file is saved in $_FILES,

<?<span>php
    </span><span>echo</span> '_FILES: <pre class="brush:php;toolbar:false">'<span>;
</span><span>//</span><span><pre class="brush:php;toolbar:false"> 标签的一个常见应用就是用来表示计算机的源代码。</span>
    <span>print_r</span>(<span>$_FILES</span><span>);
      
    </span><span>echo</span> '_POST: <pre class="brush:php;toolbar:false">'<span>;
    </span><span>print_r</span>(<span>$_POST</span><span>);
</span>?>

_FILES[] is a two-dimensional array. The array[uploadFile] key name depends on the name value in the type="file" tag. It marks the uploaded file information of this control, so we can put multiple upload controls and set different names. Of course, we can also set the same name. We can put them all in an array, such as . error means error, there are several situations, 0: No error, upload is successful; 1: The file exceeds the size specified by upload_max_filesize in the PHP configuration instruction; 2: The file exceeds the size specified by MAX_FILE_SIZE in the HTML form, 3: The file is only part Upload; 4: No files uploaded. (The size issue is still not clear ╮(╯_╰)╭, so I won’t explain it for now)

<?<span>php
    </span><span>$typeWhiteList</span> = <span>array</span>('txt', 'doc', 'php', 'zip', 'exe');   <span>//</span><span> 类型白名单,过滤不允许上传的文件类型</span>
    <span>$max_size</span> = 1000000;  <span>//</span><span> 大小限制 为1M</span>
    <span>$upload_path</span> = 'D:/WAMP';    <span>//</span><span> 指定移至的目录
     
    // 1、判断是否成功上传到服务器 </span>
    <span>$error</span> = <span>$_FILES</span>['uploadFile']['error'<span>];
    </span><span>if</span>(<span>$error</span> > 0<span>){
         </span><span>switch</span>(<span>$error</span><span>){
             </span><span>case</span> 1: <span>exit</span>('超过php配置的最大文件上传限制'<span>);
             </span><span>case</span> 2: <span>exit</span>('超过HTML表单的最大文件上传限制'<span>);
             </span><span>case</span> 3: <span>exit</span>('文件只有部分被上传'<span>);
             </span><span>case</span> 4: <span>exit</span>('没有上传任何文件'<span>);
             </span><span>default</span>: <span>exit</span>('未知类型错误'<span>);
         }
    }
     
    </span><span>//</span><span> 2、判断是否为允许上传的类型</span>
    <span>$extension</span> = <span>pathinfo</span>(<span>$_FILES</span>['uploadFile']['name'], PATHINFO_EXTENSION); <span>//</span><span> 获取扩展名</span>
    <span>if</span>(!<span>in_array</span>(<span>$extension</span>, <span>$typeWhiteList</span><span>)){
        </span><span>if</span>(<span>$extension</span> == ''<span>)
           </span><span>exit</span>('不允许上传空类型文件'<span>);
         </span><span>else</span> 
           <span>exit</span>('不允许上传'.<span>$extension</span>.'类型文件'<span>);
    } 
     
    </span><span>//</span><span> 3、判断是否为允许大小</span>
    <span>if</span>(<span>$_FILES</span>['uploadFile']['size'] > <span>$max_size</span><span>){
        </span><span>exit</span>('超过了允许上传到的'.<span>$max_size</span>.'字节'<span>);
    }
     
    </span><span>//</span><span> 4、已到指定位置</span>
    <span>$filename</span> = <span>date</span>('Ymd').<span>rand</span>(1000, 9999);   <span>//</span><span> 生成一个新文件名,防止覆盖</span>
    <span>if</span>(<span>is_uploaded_file</span>(<span>$_FILES</span>['uploadFile']['tmp_name'])){   <span>//</span><span> 判断是否通过HTTP POST上传</span>
        <span>if</span>(!<span>move_uploaded_file</span>(<span>$_FILES</span>['uploadFile']['tmp_name'], <span>$upload_path</span>.<span>$filename</span>.'.'.<span>$extension</span><span>)){
            </span><span>exit</span>('无法移动到指定位置'<span>);
         }
         </span><span>else</span><span>{
            </span><span>echo</span> '文件上传成功<br/>'<span>;
            </span><span>echo</span> '文件名: '.<span>$upload_path</span>.<span>$filename</span>.'.'.<span>$extension</span>.'<br>'<span>;
         }
    }
     </span><span>else</span><span>{
         </span><span>exit</span>('文件未通过合法途径上传'<span>);
     }</span>

Upload completed............

File download---> To download a single file, you only need to use an HTML link. Use the tag and href attribute to specify the resource location. Just click. However, this method can only handle MIME types that are not recognized by the browser by default. (MIME details are attached to wikipedia http://zh.wikipedia.org/wiki/Multipurpose Internet Mail Extensions)

<html>
    <head>
             <title>donwload <span>file</span></title>
             <meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
    </head>
    <body>
             <a href="resource/header.txt"><span>header</span>.txt</a><br/>
             <a href="resource/php.zip">php.zip</a><br/>
             <a href="resource/pic.ico">pic.ico</a>
           
    </body>
</html>

For these types of files that are not recognized by the browser, click on the link and it will directly pop up a box for you to download. Some browsers even download it directly. So for text, txt, jpg and other types of files that are recognized by browsers by default, Once clicked, it will be displayed directly on the page, such as header.txt and pic.ico above. How to download them without displaying them on the page, use the header function.

The header function will notify you by sending header information. Please treat the file as an attachment, so that it will be downloaded when clicked. (I don’t understand it very well yet, I will add more when I fully understand it ╮(╯_╰)╭)

Oh~                                                                                                                                                                                                               

State again the reprint address http://www.cnblogs.com/lazycat-cz/p/4113037.html

http://www.bkjia.com/PHPjc/971767.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/971767.htmlTechArticlePHP---File upload and download, reproduced from http://www.cnblogs.com/lazycat-cz/ p/4113037.html Security performance---the level is not enough╮(╯_╰)╭ File upload---upload local files to the service...
Statement
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
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

See all articles

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 Tools

MinGW - Minimalist GNU for Windows

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.

MantisBT

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools