2014-12-07 40 views
1

我有这块代码不能正确执行,它让我疯狂!为什么first if语句总是执行?

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"); 
    } 
} 

$这个 - >上传为$从HTML后_FILES

$这个 - >的formInput是$ _ POST从HTML后

问题是与隐藏字段 'currentImage',萤火虫表演它是明确的。然而,最后的else循环是被设置的。它仅适用于$ _ POST返回true [ 'currentImage']正在如果我改变的代码如下设置:

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

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

所以ELSEIF或 '否则,如果' 返回false,但简单的如果返回true?

+0

这听起来像第一条件为真,那么它甚至不检查其他条件 – dave 2014-12-07 06:33:22

+0

你的第一个if返回true,所以elseif永远不会被执行。 – MisterBla 2014-12-07 06:33:38

+0

我建议通过缓存'isset'操作的结果来简化代码,使其更具可读性。 – Dai 2014-12-07 06:33:48

回答

1

什么,你只需要简单地理解此处是内部elseif块的任何执行当以前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

+0

是的,我刚刚意识到它总是从每个人发布的评论以及测试各种代码中设置。感谢您展示如何检查上传的错误。我实际上是通过将isset($ this-> formInput ['image'])添加到我的第一个if语句中来实现它的,但是您放入的显然是更好的测试方法。我以为其他人是唯一的代码块,因为它也被设置好;必须不止一次地运行代码。 – 2014-12-07 06:51:00

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. 
}