为什么第一个if语句总是执行?

时间:2014-12-07 06:29:46

标签: php html5 upload

我有这段代码无法正确执行,它让我疯狂!

private function verifyImage() {
    if (!is_null($this->uploads) && array_key_exists('image', $this->uploads)) {
        $image = $this->uploads['image'];
        $tmpPath =  $image['tmp_name'];
        if ( !empty($tmpPath) ) {
            $newName = $this->userName . "." . pathinfo($image['name'],PATHINFO_EXTENSION);
            move_uploaded_file($tmpPath, __ROOT__ . '/images/' . $newName);
            $this->image = __WEBROOT__ . '/images/' . $newName;
        }
    } elseif ( isset($this->formInput['currentImage']) ) {
        $this->image = trim($this->formInput['currentImage']);
    } elseif ( isset($this->formInput['image']) && !empty($this->formInput['image']) )  {
        $this->image = trim($this->formInput['image']);
    } else {
        $this->setError('image',"Error with image field");
    }
}

$ this-> uploads是来自html post

的$ _FILES

$ this-> formInput是来自html post的$ _POST

问题在于隐藏字段' currentImage',firebug显示它已明确设置。然而,最后的else循环是设置的。如果我按如下方式更改代码,它只会在$ _POST [' currentImage']中返回true:

来自:} elseif ( isset($this->formInput['currentImage']) ) {

至:} if ( isset($this->formInput['currentImage']) ) {

所以elseif或者'否则如果'返回false,但是一个简单的if返回true?

2 个答案:

答案 0 :(得分:1)

这里您只需要了解的是,当前一个elseif语句为false时,if块内的任何内容都只执行

但是当你将它改为简单的if语句时,它只会检查if语句中的给定表达式是否为true。

在您的情况下,if (!is_null($this->uploads) && array_key_exists('image', $this->uploads)) {变为true,因为在PHP中,如果表单有文件输入(或不输入),则无论如何都设置FILES。这就是为什么它永远不会到达旁边的elseif声明。

检查文件是否上传的正确方法是,

if($this->uploads['image']['error'] != 0)
{
   // If a upload is set, this will be executed

   $image = $this->uploads['image'];
    $tmpPath =  $image['tmp_name'];
    if ( !empty($tmpPath) ) {
        $newName = $this->userName . "." . pathinfo($image['name'],PATHINFO_EXTENSION);
        move_uploaded_file($tmpPath, __ROOT__ . '/images/' . $newName);
        $this->image = __WEBROOT__ . '/images/' . $newName;
    }
}
elseif ( isset($this->formInput['currentImage']) ) {
    $this->image = trim($this->formInput['currentImage']);
} elseif ( isset($this->formInput['image']) && !empty($this->formInput['image']) )  {
    $this->image = trim($this->formInput['image']);
} else {
    $this->setError('image',"Error with image field");
}

有关详细信息,请访问http://php.net/manual/en/reserved.variables.files.php

答案 1 :(得分:0)

// php constant UPLOAD_ERR_OK,Value: 0; There is no error, the file uploaded with success.
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) { 
// do uploading
} else { 
// your error msg goes here.
}