Home php教程 php手册 用菜鸟的眼光浅谈php上传文件

用菜鸟的眼光浅谈php上传文件

Jun 21, 2016 am 08:48 AM
file files nbsp quot

本人由于想写个discuz插件,这个插件功能上涉及到上传文件这一功能,故以菜鸟的眼光来学习了下php上传文件。

 

首先,w3cshool查了下案例,觉得他说的非常详细,连我这个菜鸟都略懂了一二。

 

贴上地址:http://www.w3school.com.cn/php/php_file_upload.asp

 

照着这个讲解,写了下他这个demo,贴上代码:

 

html:

 

   

   

   

   

这个表单页,作为php菜鸟的我说下我在这个里面学到的新东西:

 

1.form的属性enctype,百度翻译了下这个单词,才知道,这个是encode type 的缩写,就是指定往服务器传递信息的编码格式;

 

2.input的type属性file,这个专用文件上传的;

 

 

 

php:

 

复制代码

//echo phpinfo();

//var_dump($_FILES);die;

 

if((($_FILES["file"]["type"]=="image/gif")($_FILES["file"]["type"]=="image/jpeg")($_FILES["file"]["type"]=="image/pjpeg")) && ($_FILES["file"]["size"]

    if($_FILES["file"]["error"]>0){

        echo "Error: ".$_FILES["file"]["error"]."
";

    }else{

        echo "Upload: ".$_FILES["file"]["name"]."
";

        echo "Type: ".$_FILES["file"]["type"]."
";

        echo "Size: ".($_FILES["file"]["size"]/1024)."Kb
";

        echo "Stored in ".$_FILES["file"]["tmp_name"];

    }

    

    if(file_exists("upload/".$_FILES["name"]["name"])){

        echo $_FILES["file"]["name"]."already exists.";

    }else{

        move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);

        echo "Stored in: "."upload/".$_FILES["file"]["name"];

    }

}else{

    echo "Invalid file";

}

复制代码

关于调试这个demo的时候,我遇到一个问题:就是运行这个demo的时候php报出warning,表示上传不成功。

 

这个时候我就想打印出$_FILES这个变量来看看,结果打印出来发现error=1;才知道上传的文件超过了php.ini的上传文件大小,导致上传失败。

 

这里说下俺新了解的知识点:

 

  

复制代码

  PHP编程语言中的常见的$_FILES 系统函数用法有:

  $_FILES['myFile']['name'] 显示客户端文件的原名称。

  $_FILES['myFile']['type'] 文件的 MIME 类型,例如"image/gif"。

  $_FILES['myFile']['size'] 已上传文件的大小,单位为字节。

  $_FILES['myFile']['tmp_name'] 储存的临时文件名,一般是系统默认。

  $_FILES['myFile']['error'] 该文件上传相关的错误代码。以下为不同代码代表的意思:

  0; 文件上传成功。

  1; 超过了文件大小php.ini中即系统设定的大小。

  2; 超过了文件大小

  MAX_FILE_SIZE 选项指定的值。

  3; 文件只有部分被上传。

  4; 没有文件被上传。

  5; 上传文件大小为0。

复制代码

 

 

 

到这里,应该就知道了我刚刚运行demo的错误是啥导致的,那既然发现是php.ini里面限制超出了,那接下来我就修改了下php.ini的配置。

 

总结下我修改这个php.ini上传限制的感受:

首先,要修改php上传文件大小限制,那要改php.ini里面的两个参数,一个是upload_max_filesize,还有个就是post_max_size,修改下这两个参数的大小就可以了!

其次,就是找准php.ini的位置,我由于本地电脑搭建的是集成环境,所以php.ini在apache文件夹下面,如果是自己搭建的环境,那就在php文件夹下面,如果找不到,echo下phpinfo(),可以看到php.ini文件的位置。

 

那到此为止,跟我差不多的新手们就能运行w3cshool上面的demo了,完成上传实例了。

 

关于上传文件,我看了下discuz其他插件作者开发的插件,有点小收获,贴上来跟大家分享下:

复制代码

   $fileTypes  = array('mp3','wav');    //定义允许上传的文件类型

    $result     = null;

    $uploadDir  = './mail';        //上传路径

    if(!submitcheck($_POST['formhash2'])){    //检测是否是上传文件

        if($_POST['upname']==''){    //判断上传文件的命名是否为空

            $result=lang('plugin/saya_mails', 'noname');

        }else{

                $myfile = $_FILES['myfile'];    //获取上传的文件信息

                $myfileType = substr($myfile['name'], strrpos($myfile['name'], ".") + 1);    //两种获取上传文件的后缀名

            //    $myfileTyle = substr(strrchr($myfile['name'],'.'),1);

                if ($myfile['size'] > 1024*1024*1024) {    //判断上传文件大小是否超过限制

                    $result = lang('plugin/saya_mails', 'big');

                } else if (!in_array($myfileType, $fileTypes)) {    //判断是否是允许上传的类型

                    $result = lang('plugin/saya_mails', 'type');

                } elseif (is_uploaded_file($myfile['tmp_name'])) {    //判断是否是通过HTTP post上传的文件

                    $toFile = './source/plugin/saya_mails/mail/' . $myfile['name'];        //目标存储地址

                    if (@move_uploaded_file($myfile['tmp_name'], $toFile)) {    //将文件拷贝到目标存储地址     //这个地方加@是屏蔽错误信息和警告

//                    if (copy($myfile['tmp_name'],$toFile)) {

                        $end=0;

                        $result = lang('plugin/saya_mails', 'success');  

                    } else {

                        $result = lang('plugin/saya_mails', 'unknow');

                    }

                } else {

                    $result = lang('plugin/saya_mails', 'big');

                }

    }

  }

复制代码

 对比了下,w3cshool上面的上传实例,觉得这个作者写的更完善一点

 

大体流程就是:

 

  1.判断是否是上传文件,他用的这个方法是discuz自带的,我们一般用,就是form传递过来的隐藏参数的值存不存在来进行判断;

 

  2.判断上传文件的命名是否为空,这一步大家可以跳过,这个是他自己写了个input而已;

 

  3.判断上传大小是否超出;

 

  4.获取文件后缀名,判断是否是允许的上传文件类型;

 

  5.判断文件是否是通过http post上传的;

 

  6.移动保存文件;

 

关于以上流程,个人总结了下自己获得的新的知识点:

 

  1.关于获取文件的后缀名,原插件作者是通过函数strrpos()来返回"."所在的位置,然后通过截取函数substr()来获得上传文件的后缀。

 

   这里,strrpos()函数,我自己的理解应该是string return position的缩写,当然我还没查证过!这个函数是返回字符串里要查找的字符串最后出现的位置,并返回这个位置。也就是从后往前查,第一次出现的位置。参考地址:http://www.w3school.com.cn/php/func_string_strrpos.asp

 

     这里原作者用这个方法来判断,肯定是可以的,我百度了下,发现也可以用strrchr()和substr()函数合作来实现这个方法,我把我想的方法注释在了上面源代码里面了,其实差不多,strrchr()函数就是返回最后一次出现的要查找的字符串到结尾的字符串,参考地址:http://www.w3school.com.cn/php/func_string_strrchr.asp

 

    通过以上两种方法来判断上传文件的类型是否达标,而不是通过$_FILES["file"]["type"]来判断,这样更好判断点,对于新手,因为只要你打印下$_FILES这个参数你就知道了,type属性没这么判断来的清晰明了。

 

  2.通过is_uploaded_file()来判断文件是否是通过http上传的

 

  3.move_uploaded_file()前面的@是用来屏蔽错误信息和警告的



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)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to Fix Activation Error Code 0xc004f069 in Windows Server How to Fix Activation Error Code 0xc004f069 in Windows Server Jul 22, 2023 am 09:49 AM

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using

See all articles