我有这段代码无法正确执行,它让我疯狂!
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?
答案 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.
}