如何查看用户是否用PHP上传了文件?

我进行某种形式的验证,以确保用户上传的文件的类型正确。但是上载是可选的,因此如果他没有上载任何内容并提交了表单的其余部分,我想跳过验证。我如何检查他是否上传了东西?会$_FILES['myflie']['size'] <=0工作吗?



吃鸡游戏
浏览 443回答 3
3回答

蛊毒传说

您可以使用is_uploaded_file():if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {&nbsp; &nbsp; echo 'No upload';}从文档:如果以filename命名的文件是通过HTTP POST上传的,则返回TRUE。这有助于确保恶意用户没有试图诱使该脚本在不应该对其运行的文件上工作,例如/ etc / passwd。如果上传的文件所做的任何事情都可能向用户甚至同一系统上的其他用户透露其内容,则这种检查尤为重要。编辑:我在FileUpload类中使用它,以防万一:public function fileUploaded(){&nbsp; &nbsp; if(empty($_FILES)) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; $this->file = $_FILES[$this->formField];&nbsp; &nbsp; if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){&nbsp; &nbsp; &nbsp; &nbsp; $this->errors['FileNotExists'] = true;&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; return true;}

慕村9548890

这段代码对我有用。我正在使用多个文件上传,因此我需要检查是否有任何上传。HTML部分:<input name="files[]" type="file" multiple="multiple" />PHP部分:if(isset($_FILES['files']) ){&nbsp;&nbsp;foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){&nbsp; &nbsp; &nbsp; if(!empty($_FILES['files']['tmp_name'][$key])){&nbsp; &nbsp; //&nbsp; things you want to do&nbsp; &nbsp; }}

牛魔王的故事

我不得不重写他的示例以适合我的目的。他的示例假定提交字段的名称是已知的并且可以用硬编码输入。我进一步走了一步,制作了一个函数,该函数将告诉我是否有任何文件被上传,而不必知道上传字段的名称。/**&nbsp;* Tests all upload fields to determine whether any files were submitted.&nbsp;*&nbsp;&nbsp;* @return boolean&nbsp;*/function files_uploaded() {&nbsp; &nbsp; // bail if there were no upload forms&nbsp; &nbsp;if(empty($_FILES))&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; // check for uploaded files&nbsp; &nbsp; $files = $_FILES['files']['tmp_name'];&nbsp; &nbsp; foreach( $files as $field_title => $temp_name ){&nbsp; &nbsp; &nbsp; &nbsp; if( !empty($temp_name) && is_uploaded_file( $temp_name )){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // found one!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; // return false if no files were found&nbsp; &nbsp;return false;}
打开App,查看更多内容
随时随地看视频慕课网APP