如何查看用户是否用PHP上传了文件? [英] How to check whether the user uploaded a file in PHP?

查看:82
本文介绍了如何查看用户是否用PHP上传了文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行某种形式的验证,以确保用户上传的文件的类型正确.但是上载是可选的,因此如果他没有上载任何内容并提交了表单的其余部分,我想跳过验证.我该如何检查他是否上传了东西? $_FILES['myflie']['size'] <=0可以工作吗?

I do some form validation to ensure that the file a user uploaded is of the right type. But the upload is optional, so I want to skip the validation if he didn't upload anything and submitted the rest of the form. How can I check whether he uploaded something or not? Will $_FILES['myflie']['size'] <=0 work?

推荐答案

您可以使用

You can use is_uploaded_file():

if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
    echo 'No upload';
}

从文档中

如果名称为的文件返回TRUE 文件名是通过HTTP POST上传的. 这有助于确保 恶意用户没有试图欺骗 该脚本可以处理文件 它不应该工作-对于 实例/etc/passwd.

Returns TRUE if the file named by filename was uploaded via HTTP POST. This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files upon which it should not be working--for instance, /etc/passwd.

这种检查尤其 重要的是,如果有机会 上载文件完成的所有操作 可以向他们透露他们的内容 用户,甚至是其他用户 同一系统.

This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

我在FileUpload类中使用它,以防它起作用:

I'm using this in my FileUpload class, in case it helps:

public function fileUploaded()
{
    if(empty($_FILES)) {
        return false;       
    } 
    $this->file = $_FILES[$this->formField];
    if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
        $this->errors['FileNotExists'] = true;
        return false;
    }   
    return true;
}

这篇关于如何查看用户是否用PHP上传了文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆