使用PHP创建单文件上传表单的最佳方式是什么? [英] What's the best way to create a single-file upload form using PHP?

查看:159
本文介绍了使用PHP创建单文件上传表单的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上发现了一些样本,但是我希望从每天使用PHP的人那里得到有关潜在安全性或性能考虑及其解决方案的反馈。

请注意,我一次只上传一个文件。
$ b 理想情况下,不需要浏览器插件(Flash / Java),但是知道使用插件的好处。



我想知道最好的HTML表单代码和PHP处理代码。

解决方案

文件上传教程



HTML



 < form enctype =multipart / form-dataaction =action.phpmethod =POST> 
< input type =hiddenname =MAX_FILE_SIZEvalue =1000000/>
< input name =userfiletype =file/>
< input type =submitvalue =Go/>
< / form>




  • action.php 是处理上载的PHP文件的名称(如下所示)
  • MAX_FILE_SIZE 键入文件。这个值很容易在客户端操纵,所以不应该依赖。它的主要好处是在用户上传文件之前提前告知用户文件太大。

  • 你可以用<$ c $类型改变输入的名字c> file ,但确保它不包含任何空格。您还必须更新PHP文件中相应的值(如下)。

    $ b $ h

    $ b

     <?php 
    $ uploaddir =/ www / uploads /;
    $ uploadfile = $ uploaddir。基名($ _ FILES [ userfile的] [名称]);

    echo'< pre>';
    if(move_uploaded_file($ _ FILES ['userfile'] ['tmp_name'],$ uploadfile)){
    echoSuccess.\\\
    ;
    } else {
    echoFailure.\\\
    ;
    }

    echo'这是一些更多的调试信息:';
    print_r($ _ FILES);
    打印< / pre>;
    ?>

    上传到文件夹不应位于可通过HTTP访问的位置,否则应该是可以上传一个PHP脚本并在服务器上执行。



    打印 $ _ FILES 的值可以给出暗示发生了什么事情。例如:



    $ b $ user

    $ b [name] => Filename.ext
    [type] =>
    [tmp_name] =>
    [error] => 2
    [size] => 0


    这个结构给出了关于文件名,MIME类型,大小和错误代码的一些信息。 >

    错误代码




    0表示没有错误,文件已经成功上传<
    1表示该文件超过了php.ini中定义的最大文件大小。如果你想改变最大的文件大小,你需要打开你的php.ini文件,确定这一行:upload_max_filesize = 2M,并将值从2M(2MB)更改为任何你需要的值
    2表示手动定义的最大文件大小超过了页面脚本中的内容

    3表示文件仅被部分上载

    4表示文件未被指定(空文件字段)

    5未定义

    6表示没有临时文件夹

    7表示文件无法写入磁盘



    php.ini 配置



    使用较大的文件运行此设置时,您可能会收到错误。检查您的 php.ini 文件中的这些键:

    max_execution_time = 30

    upload_max_filesize = 2M



    根据需要增加这些值可能会有所帮助。使用Apache时,对该文件的更改需要重新启动。



    允许的最大内存值(通过 memory_limit 设置)在这里不起作用,因为文件被上传到tmp目录。 tmp目录的位置可通过 upload_tmp_dir



    检查文件mimetypes



    您应该检查用户正在上传的文件类型 - 最好的做法是根据允许的文件类型列表进行验证。允许任何文件的潜在风险是:用户可能会将PHP代码上传到服务器,然后运行它



    您可以使用非常有用 fileinfo 扩展名(取代旧的

      // //将FILEINFO_MIME设置为返回 函数)来验证mime类型。 MIME类型,将返回信息的字符串,否则
    $ fileinfo = new finfo(FILEINFO_MIME);
    $ file = $ fileinfo->文件($ _ FILE ['filename']);

    $ allowed_types = array('image / jpeg','image / png');
    if(!in_array($ file,$ allowed_types))
    {
    die('文件类型'。$ file。'不允许上传');

    $继续
    $ / code $ / pre
    $ b $ h2更多信息

    您可以在 PHP.net手册



    对于PHP 5.3 +



      //对于那些使用PHP 5.3的人来说,代码是不一样的。 
    $ fileinfo = new finfo(FILEINFO_MIME_TYPE);
    $ file = $ fileinfo-> file($ _ FILE ['filename'] ['tmp_name']);
    $ allowed_types = array('image / jpeg','image / png');
    if(!in_array($ file,$ allowed_types))
    {
    die('文件类型'。$ file。'不允许上传');

    $继续
    $ / code $ / pre
    $ b $ h2更多信息

    您可以在 PHP.net文档中的FILEINFO_MIME_TYPE上阅读更多信息


    I've found a few samples online but I'd like to get feedback from people who use PHP daily as to potential security or performance considerations and their solutions.

    Note that I am only interested in uploading a single file at a time.

    Ideally no browser plugin would be required (Flash/Java), although it would be interesting to know the benefits of using a plugin.

    I would like to know both the best HTML form code and PHP processing code.

    解决方案

    File Upload Tutorial

    HTML

    <form enctype="multipart/form-data" action="action.php" method="POST">
      <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
      <input name="userfile" type="file" />
      <input type="submit" value="Go" />
    </form>
    

    • action.php is the name of a PHP file that will process the upload (shown below)
    • MAX_FILE_SIZE must appear immediately before the input with type file. This value can easily be manipulated on the client so should not be relied upon. Its main benefit is to provide the user with early warning that their file is too large, before they've uploaded it.
    • You can change the name of the input with type file, but make sure it doesn't contain any spaces. You must also update the corresponding value in the PHP file (below).

    PHP

    <?php
    $uploaddir = "/www/uploads/";
    $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
    
    echo '<pre>';
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "Success.\n";
    } else {
        echo "Failure.\n";
    }
    
    echo 'Here is some more debugging info:';
    print_r($_FILES);
    print "</pre>";
    ?>
    

    The upload-to folder should not be located in a place that's accessible via HTTP, otherwise it would be possible to upload a PHP script and execute it upon the server.

    Printing the value of $_FILES can give a hint as to what's going on. For example:

        Array
        (
            [userfile] => Array
            (
                [name] => Filename.ext
                [type] => 
                [tmp_name] => 
                [error] => 2
                [size] => 0
            )
        )
    

    This structure gives some information as to the file's name, MIME type, size and error code.

    Error Codes

    0 Indicates that there was no errors and file has been uploaded successfully
    1 Indicates that the file exceeds the maximum file size defined in php.ini. If you would like to change the maximum file size, you need to open your php.ini file, identify the line which reads: upload_max_filesize = 2M and change the value from 2M (2MB) to whatever you need
    2 Indicates that the maximum file size defined manually, within an on page script has been exceeded
    3 Indicates that file has only been uploaded partially
    4 Indicates that the file hasn't been specified (empty file field)
    5 Not defined yet
    6 Indicates that there´s no temporary folder
    7 Indicates that the file cannot be written to the disk

    php.ini Configuration

    When running this setup with larger files you may receive errors. Check your php.ini file for these keys:

    max_execution_time = 30
    upload_max_filesize = 2M

    Increasing these values as appropriate may help. When using Apache, changes to this file require a restart.

    The maximum memory permitted value (set via memory_limit) does not play a role here as the file is written to the tmp directory as it is uploaded. The location of the tmp directory is optionally controlled via upload_tmp_dir.

    Checking file mimetypes

    You should check the filetype of what the user is uploading - the best practice is to validate against a list of allowed filetypes. A potential risk of allowing any file is that a user could potentially upload PHP code to the server and then run it.

    You can use the very useful fileinfo extension (that supersedes the older mime_content_type function) to validate mime-types.

    // FILEINFO_MIME set to return MIME types, will return string of info otherwise
    $fileinfo = new finfo(FILEINFO_MIME);
    $file = $fileinfo->file($_FILE['filename']);
    
    $allowed_types = array('image/jpeg', 'image/png');
    if(!in_array($file, $allowed_types))
    {
        die('Files of type' . $file . ' are not allowed to be uploaded.');
    }
    // Continue
    

    More Information

    You can read more on handling file uploads at the PHP.net manual.

    For PHP 5.3+

    //For those who are using PHP 5.3, the code varies.
    $fileinfo = new finfo(FILEINFO_MIME_TYPE);
    $file = $fileinfo->file($_FILE['filename']['tmp_name']);
    $allowed_types = array('image/jpeg', 'image/png');
    if(!in_array($file, $allowed_types))
    {
        die('Files of type' . $file . ' are not allowed to be uploaded.');
    }
    // Continue
    

    More Information

    You can read more on FILEINFO_MIME_TYPE at the PHP.net documentation.

    这篇关于使用PHP创建单文件上传表单的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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