html的input表单上传文件的方法


结合php的上传方法,不使用插件,上传单文件

HTML php

森之猎人与弓 10 years, 10 months ago

我其实很想丢一句 「你给我去搜索啊啊啊!」 就不管你了 ...

但考虑到搜索的结果水平良莠不齐 ... 有些还错误百出 ... 误导你不好 ... 还是给你写一个吧 ...

再说这问题放一天了没人理怪可怜的不是 ... 恩 ... 代码如下 ...

<?php
/* very simple template manager ... all html pages defined here ... */
$template = function( $name, $param ) { $html = [

/* a simple upload form ... */
'UPLOAD_FORM'       =>  function( $action ) { 
    return <<< UPLOAD_FORM
<html><head><title>Upload Example - 
  Step 1 - Choose File</title>
<body><form action="{$action}" method="post" 
  enctype="multipart/form-data">
  <!-- MAX_FILE_SIZE will parsed before your script runs ... -->
  <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
  <input type="file" name="file" />
  <input type="submit" value="Upload" />
</form></body></html>
UPLOAD_FORM;
},

/* a simple error page ... */
'UPLOAD_ERROR'      =>  function( $message ) {
    return <<< UPLOAD_ERROR
<html><head><title>Upload Example - 
  Step 2.1 - Error Occurs When Uploading</title>
<body><h2>Error</h2>
  <p>{$message}</p>
</body></html>
UPLOAD_ERROR;
},

/* simple upload result page appears BEFORE file moved ... */
'UPLOAD_RESULT_1'     =>  function( array $info ) {
    return <<< UPLOAD_RESULT_1
<html><head><title>Upload Example - 
  Step 2.2 - Show Uploaded File Info</title>
<body><h2>Basic File Info</h2><dl>
  <dt>Name :</dt><dd>{$info['name']}</dd>
  <dt>Type :</dt><dd>{$info['type']}</dd>
  <dt>Size :</dt><dd>{$info['size']}</dd>
  <dt>Path :</dt><dd>{$info['tmp_name']}</dd>
</dl>

UPLOAD_RESULT_1;

},

/* simple upload result page appears AFTER file moved ... */
'UPLOAD_RESULT_2'     =>  function( array $result ) {
    return <<< UPLOAD_RESULT_2
<h2>Final Processing Result</h2><dl>
  <dt>From :</dt><dd>{$result['from']}</dd>
  <dt>Move To :</dt><dd>{$result['to']}</dd>
  <dt>Status :</dt><dd>{$result['status']}</dd>
</dl></body></html>
UPLOAD_RESULT_2;

} ];

/* show the page off ... */
echo isset( $html[$name] ) ? $html[$name]($param) : ''; 
return;

};

/* define where uploaded file should stored in ... */
define( 'UPLOAD_PATH', 'upload' );

/* simple way to judge whether we got a file or not ... */
if ( ! isset( $_FILES['file'] ) )

    /* no file ..? time to upload ... */
    $template( 'UPLOAD_FORM', $_SERVER['PHP_SELF'] );

/* well ... it seems that we have something to do ... */
else {

    /* let us rock ... */
    try {

        /* make an alias and make sure our file uploaded normally ... */
        if ( UPLOAD_ERR_OK === ( $error = $_FILES['file']['error'] ) ) {

            /* hooray ... show the result and make another alias ... */
            $template( 'UPLOAD_RESULT_1', ( $file = $_FILES['file'] ) );

            /* this is not the end ... we need to confirm this file ... */
            $checker = function( $file ) {

                /* you can deny a file if it too large ... */
                if ( $file['size'] > 1234 );

                /* you can also deny a file if you do not want it ... */
                if ( ! in_array( 
                    $file['type'], [ 'image/jpeg', 'image/png' ]
                    ) );

                /* you can even specify the file name ... */
                if ( 'Sunyanzi.zip' !== $file['name'] );

                /* in a word ... do everything you want here ... */
                return true;

            };

            /* initialize the result array ... */
            $result = [
                'from'  =>  $file['tmp_name'],
                'to'    =>  
                    $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 
                    UPLOAD_PATH . DIRECTORY_SEPARATOR . $file['name'],
                'status'   =>  'Failure'
                ];

            /* is the file passed our examination ..? */
            if ( true === $checker( $file ) ) {

                /* prepare store path ... */
                if ( ! is_dir( UPLOAD_PATH ) ) 
                    mkdir( UPLOAD_PATH, 0755, true );

                /* move file to the right place and keep its name ... */
                if ( move_uploaded_file( $file['tmp_name'], 
                    UPLOAD_PATH . DIRECTORY_SEPARATOR . $file['name'] 
                    ) )

                    /* change status to success ... */
                    $result['status'] = 'Success';

            }

            /* show the final result and we have done ... */
            $template( 'UPLOAD_RESULT_2', $result );

        /* something wrong with it ..? */
        } else {

            /* failure ..? what happened ..? let us find it out ! */
            $error_messages = [
                UPLOAD_ERR_INI_SIZE     =>  
                    'The uploaded file exceeds the upload_max_filesize ' .
                    'directive in php.ini.',
                UPLOAD_ERR_FORM_SIZE    =>
                    'The uploaded file exceeds the MAX_FILE_SIZE direct' .
                    'ive that was specified in the HTML form.',
                UPLOAD_ERR_PARTIAL      =>
                    'The uploaded file was only partially uploaded.',
                UPLOAD_ERR_NO_FILE      =>
                    'No file was uploaded.',
                UPLOAD_ERR_NO_TMP_DIR   =>
                    'Missing a temporary folder.',
                UPLOAD_ERR_CANT_WRITE   =>
                    'Failed to write file to disk.',
                UPLOAD_ERR_EXTENSION    =>
                    'A PHP extension stopped the file upload.'
                ];

            /* throw the error out ! */
            throw new Exception( 
                isset( $error_messages[$error] ) ?
                    $error_messages[$error] : 'Unknown Error'
                );

        }

    /* something wrong ..? */
    } catch ( Exception $ex ) {

        /* show it out ... */
        $template( 'UPLOAD_ERROR', $ex->getMessage() );

    }


}

没写什么花哨的东西 ... 整个流程很简单 ...

最开始是定义所有用到的 html 页面 ... 然后是定义上传路径 ... 然后就是上传的部分 ...

看一下有哪里不明白可以再问 ...

以及说 ... 我的 $checker 只是用于演示 ... 所以写的很简单 ...

但事实上开放用户自由上传是一个 很危险 的行为 ... 如果你确定要用 ... 一定要再三确保安全 ...

恩就是这样啦 ...

咿呀咿呀咿呀 answered 10 years, 10 months ago

Your Answer