is_uploaded_file

(PHP 3 >= 3.0.17, PHP 4 >= 4.0.3, PHP 5)

is_uploaded_file -- 判断文件是否是通过 HTTP POST 上传的

说明

bool is_uploaded_file ( string filename )

如果 filename 所给出的文件是通过 HTTP POST 上传的则返回 TRUE 。这可以用来确保恶意的用户无法欺骗脚本去访问本不能访问的文件,例如 /etc/passwd

这种检查显得格外重要,如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。

为了能使 is_uploaded_file() 函数正常工作,必段指定类似于 $_FILES['userfile']['tmp_name'] 的变量,而在从客户端上传的文件名 $_FILES['userfile']['name'] 不能正常运作。

例子 1. is_uploaded_file() 例子

<?php

if ( is_uploaded_file ( $_FILES [ 'userfile' ][ 'tmp_name' ])) {
   echo
"File " . $_FILES [ 'userfile' ][ 'name' ] . " uploaded successfully.\n" ;
   echo
"Displaying contents\n" ;
   
readfile ( $_FILES [ 'userfile' ][ 'tmp_name' ]);
} else {
   echo
"Possible file upload attack: " ;
   echo
"filename '" . $_FILES [ 'userfile' ][ 'tmp_name' ] . "'." ;
}

?>

is_uploaded_file() 仅可用于 PHP 3 的 3.0.16 版之后,以及 PHP 4 的 4.0.2 版之后。如果你执意要用老版本,可以用下面的函数来保护自己:

注: 以下例子 不能 用于 PHP 4 的 4.0.2 版之后。它依赖的 PHP 内部函数在该版本之后改变了。

例子 2. is_uploaded_file() 可运行于 PHP 4 < 4.0.3 的例子

<?php
/* Userland test for uploaded file. */
function is_uploaded_file ( $filename )
{
    if (!
$tmp_file = get_cfg_var ( 'upload_tmp_dir' )) {
        
$tmp_file = dirname ( tempnam ( '' , '' ));
    }
    
$tmp_file .= '/' . basename ( $filename );
    
/* User might have trailing slash in php.ini... */
    
return ( ereg_replace ( '/+' , '/' , $tmp_file ) == $filename );
}

/* This is how to use it, since you also don't have
* move_uploaded_file() in these older versions: */
if ( is_uploaded_file ( $HTTP_POST_FILES [ 'userfile' ])) {
    
copy ( $HTTP_POST_FILES [ 'userfile' ], "/place/to/put/uploaded/file" );
} else {
    echo
"Possible file upload attack: filename '$HTTP_POST_FILES [ userfile ] '." ;
}
?>

参见 move_uploaded_file() ,以及 文件上传处理 一章中的简单使用例子。