Home php教程 php手册 PHP文件上传代码用法详解

PHP文件上传代码用法详解

Jun 13, 2016 am 10:16 AM
php upload code getting Started big how document article yes usage of edit Detailed explanation

本文章是一篇适合于php入门者的文章告诉大如何编辑php文件上传代码,在编辑前我们需要了解几点,有及FILES全局变量的理解了,有需要学习php文件上传的朋友可参考本文章。

php文件上传代码编写过程

1. 先判断是否上传文件
2. 如果有再来判断上传中是否出错
3. 如果出错,则提示出错信息
4. 如查没出错,再判断文件类型
5. 如果类型符合条件,再判断指定目录中有没有存在该文件
6. 如果没有就把该文件移至指定目录

在php中上传文件必须知道的几个东西

$_FILES['myfile']['name']  是指被上传文件的名称
$_FILES['myfile']['type']  是指被上传文件的类型
$_FILES['myfile']['size']  是指被上传文件的大小,单位为字节(B)
$_FILES['myfile']['tmp_name']  是指被上传文件存在服务器中的临时副本文件名称,文件被移动到指定目录后临文件将被自动消毁。
$_FILES['myfile']["error"]  是指由文件上传中有可能出现的错误的状态码,关于各状态含义后在会说明。


先来看一下HTML部分。

 代码如下 复制代码

?


上传:

说明:

form标答的action="upload.php"是指点击这个form中的submit的时候,这个上传命令会被发送到这个叫 upload.php的页面去处理。method="post"是指以post方式去送,enctype="multipart/form-data"属性规定了在提交这个表单时要使用哪种内容类型,在表单需要二进制数据时,比如文件内容,请使用"multipart/form-data",如果要上传文件,这个属性是必要的。input中的type="file"时,规定了应该把输入作为文件来处理,并且在input后面会有一个浏览的按钮。

我们再来看一个PHP处理页面 upload.php

 代码如下 复制代码


if($_FILES['myfile']['name'] != '') {
  if($_FILES['myfile']['error'] > 0) {
    echo "错误状态:" . $_FILES['myfile']['error'];
  } else {
    move_uploaded_file($_FILES['myfile']['tmp_name'] , "uploads/" . $FILES['myfile']['name']);
    echo "<script>alert(上传成功!);</script>";
  }
} else{
  echo "<script>alert(请上传文件!);</script>";
}
?>

上面超级简单,我们现在来升级一下


1、upload.php

 代码如下 复制代码



 


    ddd
       
      
 
       
   

       
           
           
           
           
       
请填写用户名
请简单介绍文件
请上传你的文件

   

 

2、uploadProcess.php

 代码如下 复制代码


    //接收
    $username=$_POST['username'];
    $fileintro=$_POST['fileintro'];
   
    //echo $username.$fileintro;
    //获取文件信息
/*    echo "

";<br>
    print_r($_FILES);<br>
    echo "
Copy after login
";
*/   
    //获取文件的大小
    $file_size=$_FILES['myfile']['size'];
    if($file_size>2*1024*1024){
        echo "";
        exit();
    }

    //获取文件类型
    $file_type=$_FILES['myfile']['type'];
    if($file_type!="image/jpeg" && $file_type!="image/pjpeg"){
        echo "文件类型只能是 jpg 格式";
        exit();
    }
   

    //判断上传是否OK
    if(is_uploaded_file($_FILES['myfile']['tmp_name'])){
        //得到上传的文件 转存到你希望的目录
        $upload_file=$_FILES['myfile']['tmp_name'];
       
        //防止图片覆盖问题,为每个用户建立一个文件夹   
        $user_path=$_SERVER['DOCUMENT_ROOT']."/file/up/".$username;
        if(!file_exists($user_path)){
            mkdir ($user_path);
        }

        //$move_to_file=$user_path."/".$_FILES['myfile']['name'];
        //防止用户上传用户名相同的问题
        $file_true_name=$_FILES['myfile']['name'];
        $move_to_file=$user_path."/".time().rand(1,1000).substr($file_true_name,strripos($file_true_name,"."));

        //echo $upload_file.$move_to_file;
        //中文要转码
        if(move_uploaded_file($upload_file,iconv("utf-8","gb2312","$move_to_file"))){
            echo $_FILES['myfile']['name']."上传成功";
        }else{
            echo "上传失败";
        }
    }else{
        echo "上传失败";
    }

?>

注意:

我举个例子大家就知道,比如一个图片文件 pic.jpg,我们用 strrchr处理,strrchr(pic.jpg,'.'),它将返回.jpg,明白了吗?该函数返回指定字符在该字符串最后出现的位置后的字符。配合 substr() 我们就可以取到jpg,这样我们就得到了文件的后缀名,来判断上传文件是否符合指定格式。本程序把指定的格式放在一个数组中,实际使用时可根据需要添加。
    接下来看产生随机数文件名部分, 我们看到mt_srand()这个函数,手册上叫他“播下一个更好的随机数发生器种子”,其实就是初始化一个随机数的函数,参数是(double)microtime() * 1000000,这里如果不这是参数就会自动设置个随机数,当然这不符合我们的需要,如此一来,随机数就具备一定的长度,保证了上传文件不重名

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles