附加Php文件而不附加声明

时间:2016-01-06 17:04:07

标签: php

我有一个代码

if(count($_FILES) > 0) {
    foreach($_FILES['fileAttach']['error'] as $status){
        if($status === UPLOAD_ERR_OK) {
        $fname[] = $_FILES['fileAttach']['name'][$Ccount];
        $tmp_path[] = $_FILES['fileAttach']['tmp_name'][$Ccount];
        $ftype[] =  $_FILES['fileAttach']['type'][$Ccount];
        }
        $Ccount++;
    }
} else { $fname[] = "0"; $tmp_path[] = "0"; $ftype[] = "0"; } // this not working

然后我想在函数中使用变量

SendEmails($ReCEmail,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftype,$tmp_path);

在附加文件之前一直有效,但如果没有,我会收到错误Notice: Undefined variable: fname in ... on line ..

function SendEmails($vasia,$strSubject,$strMessage,$txtFormName,$txtFormEmail,$fname,$ftypes,$tmp_path) {

if(count($fname) == 0) 
        { code without variables $fname,$ftypes,$tmp_path } 
else {code with variables $fname,$ftypes,$tmp_path}
}

如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

如果所有$ _FILES都是错误的,那么files array将为零。所以打印出这个错误

$fname[] = array();
$tmp_path[] = array();
$ftype[] = array();

    foreach($_FILES['fileAttach']['error'] as $key => $status){
        if($status === 0) {
        $fname[] = $_FILES['fileAttach']['name'][$key];
        $tmp_path[] = $_FILES['fileAttach']['tmp_name'][$key];
        $ftype[] =  $_FILES['fileAttach']['type'][$key];
        }
    }

      if(count($fname)==0)
     { $fname[] = "0";$tmp_path[] = "0"; $ftype[] = "0"; }

答案 1 :(得分:1)

if(count(array_filter($_FILES['fileAttach']['name'])) > 0) {
    foreach($_FILES['fileAttach']['error']  as $key => $status){
        if($status === 0) {
        $fname[] = $_FILES['fileAttach']['name'][$key];
        $tmp_path[] = $_FILES['fileAttach']['tmp_name'][$key];
        $ftype[] =  $_FILES['fileAttach']['type'][$key];
        }
    }
} else { $fname[] = "0"; $tmp_path[] = "0"; $ftype[] = "0"; }

并在您的功能更改

if(count(array_filter($fname)) == 0) 

答案 2 :(得分:0)

在if:

之前初始化$ fname数组
$fname = array();
if($status === UPLOAD_ERR_OK) {

在if:

之后放置并回显,确认您的上传过程正常
if($status === UPLOAD_ERR_OK) {
        echo "Upload Status: " . $status . "<br>";
        $fname[] = $_FILES['fileAttach']['name'][$Ccount];

如果echo输出显示$ status!= UPLOAD_ERR_OK,则$ fname未初始化,因此未定义变量错误。

如果上传失败,请创建另一个问题,其中包含该问题的相应代码段。