如果 filename 所给出的文件是通过 HTTP POST 上传的则返回 TRUE。这可以用来确保恶意的用户无法欺骗脚本去访问本不能访问的文件,例如 /etc/passwd。
这种检查显得格外重要,如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。
is_uploaded_file() 仅可用于 PHP 3 的 3.0.16 版之后,以及 PHP 4 的 4.0.2 版之后。如果你执意要用老版本,可以用下面的函数来保护自己:
注: 以下例子不能用于 PHP 4 的 4.0.2 版之后。它依赖的 PHP 内部函数在该版本之后改变了。
<?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(),以及文件上传处理一章中的简单使用例子。