Home Backend Development PHP Tutorial PHP文件上传操作和打包

PHP文件上传操作和打包

Jun 13, 2016 pm 12:16 PM
gt quot return

PHP文件上传操作和封装

PHP文件上传主要两个步骤:

1.首先前端html写好文件表单上传网页

2.在前端点提交时,web服务器php脚本通过超全局变量$_FILES和一个move_uploaded_file函数搞定

前端html如下:

    <meta charset="utf-8">    <title>文件上传</title>    
Copy after login
注:表单上传文件时,method必须用post,且须声明是enctype="multipart/form-data"

2.服务器php脚本upload.php代码如下:

<?phpif (move_uploaded_file($_FILES[&#39;uploadpic&#39;][&#39;tmp_name&#39;], &#39;./fileupload/&#39;.$_FILES[&#39;uploadpic&#39;][&#39;name&#39;])){    echo "ok";    }else {    echo "fail";}
Copy after login
注:可以用print_r($_FILES)打印查看超全局变量里面放的内容,可以看到文件的相关信息都放在这个变量里面;如

array (  'uploadpic' =>   array (    'name' => '1客栈首页.jpg',    'type' => 'image/jpeg',    'tmp_name' => 'C:\\Windows\\Temp\\php3F1C.tmp',    'error' => 0,    'size' => 1706919,  ),)ok
Copy after login
从变量的数组里面可以知道上传的文件名,文件类型、web服务器临时存放图片的位置(如果要更改临时存放路径,可以去php.ini里面更改),错误信息和文件大小(限制文件上传大小,也可以到php.ini里修改)。

error有如下几种:

其值为 0,没有错误发生,文件上传成功。 
其值为 1,上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。 
其值为 2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。 
其值为 3,文件只有部分被上传。 
其值为 4,没有文件被上传。
其值为 6,找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。 
其值为 7,文件写入失败。PHP 5.1.0 引进。


==========文件上传封装类============

<?phpclass UpFile{    public $maxsize=2; //1M    public $errmsg="";    public $ext = "png,jpg,bmp,gif";        //上传大小是否符合    function isAllowSize($size)    {         if($size <= $this->maxsize*1024*1024)         {             return true;         }         else          {             return false;         }    }        //判断后缀名是否符合    function isAllowExt($ext)    {        return in_array(strtolower($ext), explode(',', $this->ext));    }        //获取文件后缀名    function getFileExt($file)    {        $arr = explode('.', $file);        return end($arr);    }        //图片上传,$pickey为input的name值,$save_path保存路径    function upload($pickey,$save_path)    {        if(!isset($_FILES[$pickey]))        {            return false;        }                if($_FILES[$pickey]['error'] !=0)        {            $this->errmsg = $this->getErrorType($_FILES[$pickey]['error']);            return false;        }        $file_ext = $this->getFileExt($_FILES[$pickey]['name']);        echo $file_ext;        if(!$this->isAllowExt($file_ext))        {            $this->errmsg = "文件后缀名不符合";            return false;        }        echo $_FILES[$pickey]['size'];        if(!$this->isAllowSize($_FILES[$pickey]['size']))        {            $this->errmsg = "大小超过限制";            return false;        }                $str = "abcdefjhijkmnpqrst23456789";        $filename = date("YmdHis",time()).substr(str_shuffle($str), 0,6);        $dir = $this->makeDir($save_path);        if(move_uploaded_file($_FILES[$pickey]['tmp_name'], $dir.'/'.$filename.'.'.$file_ext))        {                       return true;        }        else         {            $this->errmsg = "上传失败";            return false;        }    }    //创建目录    function makeDir($save_path)    {       $path = $save_path.'/'.date("Ymd",time());              if(is_dir($path) || mkdir($path,0777,true))  //不存在该目录文件,创建       {           echo $path;           return $path;       }       else        {           return false;       }    }        //错误类型分析    function getErrorType($error)    {        $errmsg = "";        switch ($error)        {            case 0:                $errmsg = "文件上传成功";                break;            case 1:                $errmsg = "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值";                break;            case 2:                $errmsg = "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值";                break;            case 3:                $errmsg = "文件只有部分被上传";                break;            case 4:                $errmsg = "没有文件被上传";                break;            case 6:                $errmsg = "找不到临时文件夹";                break;            case 7:                $errmsg = "文件写入失败";                break;        }        return $errmsg;    }}
Copy after login

使用如下:

<?phpinclude &#39;upfile.class.php&#39;;$upfile = new UpFile();if($upfile->upload('uploadpic', "./fileupload")){    echo "ok";}else{    echo $upfile->errmsg;}
Copy after login


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 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)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

How does Vue3 use setup syntax sugar to refuse to write return How does Vue3 use setup syntax sugar to refuse to write return May 12, 2023 pm 06:34 PM

Vue3.2 setup syntax sugar is a compile-time syntax sugar that uses the combined API in a single file component (SFC) to solve the cumbersome setup in Vue3.0. The declared variables, functions, and content introduced by import are exposed through return, so that they can be used in Vue3.0. Problems in use 1. There is no need to return declared variables, functions and content introduced by import during use. You can use syntactic sugar //import the content introduced import{getToday}from'./utils'//variable constmsg='Hello !'//function func

Use the return keyword in JavaScript Use the return keyword in JavaScript Feb 18, 2024 pm 12:45 PM

Usage of return in JavaScript requires specific code examples In JavaScript, the return statement is used to specify the value returned from a function. Not only can it be used to end the execution of a function, it can also return a value to the place where the function was called. The return statement has the following common uses: Return a value The return statement can be used to return a value to the place where the function is called. Here is a simple example: functionadd(a,b){

See all articles