search
HomeBackend DevelopmentPHP TutorialPHP文件上传操作和打包

PHP文件上传操作和封装

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

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

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

前端html如下:

    <meta charset="utf-8">    <title>文件上传</title>    
注:表单上传文件时,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";}
注:可以用print_r($_FILES)打印查看超全局变量里面放的内容,可以看到文件的相关信息都放在这个变量里面;如

array (  'uploadpic' =>   array (    'name' => '1客栈首页.jpg',    'type' => 'image/jpeg',    'tmp_name' => 'C:\\Windows\\Temp\\php3F1C.tmp',    'error' => 0,    'size' => 1706919,  ),)ok
从变量的数组里面可以知道上传的文件名,文件类型、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;    }}

使用如下:

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


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 data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use