国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
PHP文件上傳類實(shí)例詳解,
您可能感興趣的文章:
Home Backend Development PHP Tutorial Detailed explanation of PHP file upload class examples, _PHP tutorial

Detailed explanation of PHP file upload class examples, _PHP tutorial

Jul 12, 2016 am 08:54 AM
php

PHP文件上傳類實(shí)例詳解,

本文實(shí)例講述了PHP文件上傳類。分享給大家供大家參考,具體如下:

這里演示了FileUpload.class.php文件上傳類,其中用到了兩個(gè)常量,可在網(wǎng)站配置文件中定義:

define('ROOT_PATH',dirname(__FILE__)); //網(wǎng)站根目錄
define('UPDIR','/uploads/'); //上傳主目錄

具體代碼如下:

<&#63;php
  //上傳文件類
  class FileUpload {
    private $error;  //錯(cuò)誤代碼
    private $maxsize; //表單最大值
    private $type;  //類型
    private $typeArr = array('image/jpeg','image/pjpeg','image/png','image/x-png','image/gif'); //類型合集
    private $path;  //目錄路徑
    private $today;  //今天目錄
    private $name;  //文件名
    private $tmp;  //臨時(shí)文件
    private $linkpath; //鏈接路徑
    private $linktotay; //今天目錄(相對)
    //構(gòu)造方法,初始化
    public function __construct($_file,$_maxsize) {
       $this->error = $_FILES[$_file]['error'];
       $this->maxsize = $_maxsize / 1024;
       $this->type = $_FILES[$_file]['type'];
       $this->path = ROOT_PATH.UPDIR;
       $this->linktotay = date('Ymd').'/';
       $this->today = $this->path.$this->linktotay;
       $this->name = $_FILES[$_file]['name'];
       $this->tmp = $_FILES[$_file]['tmp_name'];
       $this->checkError();
       $this->checkType();
       $this->checkPath();
       $this->moveUpload();
    }
    //返回路徑
    public function getPath() {
       $_path = $_SERVER["SCRIPT_NAME"];
       $_dir = dirname(dirname($_path));
       if ($_dir == '\\') $_dir = '/';
       $this->linkpath = $_dir.$this->linkpath;
       return $this->linkpath;
    }
    //移動(dòng)文件
    private function moveUpload() {
       if (is_uploaded_file($this->tmp)) {
         if (!move_uploaded_file($this->tmp,$this->setNewName())) {
            Tool::alertBack('警告:上傳失?。?);
         }
       } else {
         Tool::alertBack('警告:臨時(shí)文件不存在!');
       }
    }
    //設(shè)置新文件名
    private function setNewName() {
       $_nameArr = explode('.',$this->name);
       $_postfix = $_nameArr[count($_nameArr)-1];
       $_newname = date('YmdHis').mt_rand(100,1000).'.'.$_postfix;
       $this->linkpath = UPDIR.$this->linktotay.$_newname;
       return $this->today.$_newname;
    }
    //驗(yàn)證目錄
    private function checkPath() {
       if (!is_dir($this->path) || !is_writeable($this->path)) {
         if (!mkdir($this->path)) {
            Tool::alertBack('警告:主目錄創(chuàng)建失??!');
         }
       }
       if (!is_dir($this->today) || !is_writeable($this->today)) {
         if (!mkdir($this->today)) {
            Tool::alertBack('警告:子目錄創(chuàng)建失敗!');
         }
       }
    }
    //驗(yàn)證類型
    private function checkType() {
       if (!in_array($this->type,$this->typeArr)) {
         Tool::alertBack('警告:不合法的上傳類型!');
       }
    }
    //驗(yàn)證錯(cuò)誤
    private function checkError() {
       if (!empty($this->error)) {
         switch ($this->error) {
            case 1 :
              Tool::alertBack('警告:上傳值超過了約定最大值!');
              break;
            case 2 :
              Tool::alertBack('警告:上傳值超過了'.$this->maxsize.'KB!');
              break;
            case 3 :
              Tool::alertBack('警告:只有部分文件被上傳!');
              break;
            case 4 :
              Tool::alertBack('警告:沒有任何文件被上傳!');
              break;
            default:
              Tool::alertBack('警告:未知錯(cuò)誤!');
         }
       }
    }
  }
&#63;>

其中,用到了一個(gè)靜態(tài)工具類 Tool.class.php,代碼如下:

Tool.class.php

<&#63;php
  class Tool {
     //彈窗返回
     static public function alertBack($_info) {
       echo "<script type='text/javascript'>alert('$_info');history.back();</script>";
       exit();
     }     //彈窗賦值關(guān)閉
     static public function alertOpenerClose($_info,$_path) {
       echo "<script type='text/javascript'>alert('$_info');</script>";
       echo "<script type='text/javascript'>opener.document.content.thumbnail.value='$_path';</script>";
       echo "<script type='text/javascript'>opener.document.content.pic.style.display='block';</script>";
       echo "<script type='text/javascript'>opener.document.content.pic.src='$_path';</script>";
       echo "<script type='text/javascript'>window.close();</script>";
       exit();
     } }
&#63;>

下面進(jìn)行一個(gè)實(shí)例演示,請看下面的步驟:

1、先創(chuàng)建一個(gè) index.php 頁面,做一個(gè)表單

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>main</title>
  </head>
  <body>
     <form name="content" method="post" action="&#63;action=add">
     <input type="text" name="thumbnail" class="text" readonly="readonly" /> <input type="button" value="上傳" onclick="centerWindow('./upfile.html','upfile','400','100')" /> <img name="pic" style="display:none;" /> ( * 必須是jpg,gif,png,并且200k內(nèi)) <br />
     </form>
  </body>
</html>

2、創(chuàng)建 upfile.html 文件,建立表單提交到 upload.php

upfile.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>上傳圖片</title>
  </head>
  <body></p><p>   <form method="post" action="./upload.php" enctype="multipart/form-data" style="text-align:center;margin:30px;">
    <input type="hidden" name="MAX_FILE_SIZE" value="204800" />
    <input type="file" name="pic" />
    <input type="submit" name="send" value="確定上傳" />
</form></p><p></body>
</html>

3、通過 upload.php 文件調(diào)用文件上傳類實(shí)現(xiàn)上傳,并且把路徑賦給 input 標(biāo)簽和顯示圖片

<&#63;php
  require 'FileUpload.class.php';
  if (isset($_POST['send'])) {
    $_fileupload = new FileUpload('pic',$_POST['MAX_FILE_SIZE']);
    $_path = $_fileupload->getPath();
    Tool::alertOpenerClose('文件上傳成功!',$_path);
  } else {
    Tool::alertBack('警告:文件過大或者其他未知錯(cuò)誤導(dǎo)致瀏覽器崩潰!');
  }
&#63;>

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php文件操作總結(jié)》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP基本語法入門教程》、《php操作office文檔技巧總結(jié)(包括word,excel,access,ppt)》、《php日期與時(shí)間用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:

  • 適用于初學(xué)者的簡易PHP文件上傳類
  • 一個(gè)完整的php文件上傳類實(shí)例講解
  • PHP多文件上傳類實(shí)例
  • php判斷文件上傳類型及過濾不安全數(shù)據(jù)的方法
  • php可生成縮略圖的文件上傳類實(shí)例
  • 一個(gè)經(jīng)典的PHP文件上傳類分享
  • php 文件上傳類代碼
  • PHP5+UTF8多文件上傳類

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1119982.htmlTechArticlePHP文件上傳類實(shí)例詳解, 本文實(shí)例講述了PHP文件上傳類。分享給大家供大家參考,具體如下: 這里演示了FileUpload.class.php文件上傳類,其中...
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

See all articles