首页 > 代码库 > 理解流方式上传和form表单上传

理解流方式上传和form表单上传

流方式上传:

$post_input = ‘php://input‘;$save_path = dirname( __FILE__ );$postdata = file_get_contents( $post_input );if ( isset( $postdata ) && strlen( $postdata ) > 0 ) {    $filename = $save_path . ‘/‘ . uniqid() . ‘.jpg‘;    $handle = fopen( $filename, ‘w+‘ );    fwrite( $handle, $postdata );    fclose( $handle );    if ( is_file( $filename ) ) {        echo ‘Image data save successed,file:‘ . $filename;        exit ();    }else {        die ( ‘Image upload error!‘ );    }}else {    die ( ‘Image data not detected!‘ );}
View Code

标准表单上传:

if (!$_FILES[‘Filedata‘]) {    die ( ‘Image data not detected!‘ );}if ($_FILES[‘Filedata‘][‘error‘] > 0) {    switch ($_FILES [‘Filedata‘] [‘error‘]) {        case 1 :            $error_log = ‘The file is bigger than this PHP installation allows‘;            break;        case 2 :            $error_log = ‘The file is bigger than this form allows‘;            break;        case 3 :            $error_log = ‘Only part of the file was uploaded‘;            break;        case 4 :            $error_log = ‘No file was uploaded‘;            break;        default :            break;    }    die ( ‘upload error:‘ . $error_log );} else {    $img_data = $_FILES[‘Filedata‘][‘tmp_name‘];    $size = getimagesize($img_data);    $file_type = $size[‘mime‘];    if (!in_array($file_type, array(‘image/jpg‘, ‘image/jpeg‘, ‘image/pjpeg‘, ‘image/png‘, ‘image/gif‘))) {        $error_log = ‘only allow jpg,png,gif‘;        die ( ‘upload error:‘ . $error_log );    }    switch($file_type) {        case ‘image/jpg‘ :        case ‘image/jpeg‘ :        case ‘image/pjpeg‘ :            $extension = ‘jpg‘;            break;        case ‘image/png‘ :            $extension = ‘png‘;            break;        case ‘image/gif‘ :            $extension = ‘gif‘;            break;    }    }if (!is_file($img_data)) {    die ( ‘Image upload error!‘ );}
View Code

 

PHP输入流php://input

在使用xml-rpc的时候,server端获取client数据,主要是通过php输入流input,而不是$_POST数组。所以,这里主要探讨php输入流php://input

对于php://input介绍,PHP官方手册文档有一段话对它进行了很明确地概述:

“php://input allows you to read raw POST data. It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives. php://input is not available with enctype=”multipart/form-data”.

翻译过来,是这样:

“php://input可以读取没有处理过的POST数据。相较于$HTTP_RAW_POST_DATA而言,它给内存带来的压力较小,并且不需要特殊的php.ini设置。php://input不能用于enctype=multipart/form-data”

我们应该怎么去理解这段概述呢?我把它划分为三部分,逐步去理解:

  1. 读取POST数据
  2. 不能用于multipart/form-data类型
  3. php://input VS $HTTP_RAW_POST_DATA

读取POST数据

PHPer们一定很熟悉$_POST这个内置变量。$_POST与php://input存在哪些关联与区别呢?另外,客户端向服务端交互数据,最常用的方法除了POST之外,还有GET。既然php://input作为PHP输入流,它能读取GET数据吗?这二个问题正是我们这节需要探讨的主要内容。

详见:

http://www.nowamagic.net/academy/detail/12220520