简体   繁体   中英

php class not executing else statement

Being a noob ... I can't quite figure out what isn't working here .... if the file is empty, $this->result contains the right error message. But if I have a file name, the result array is empty and I'm not getting an upload

class upload_f
{
    public $path;              // path to upload from root ie  files/images/
    public $fileName;          // current file  ie $_FILES['uploadedfile']['name'];
    public $result = array();  // array containing error to be loop outside object

    public function validateInput()       // verify is minimal data is entered.
    {

        if (empty($this->fileName))
        {
            $this->result[] = "ERROR: File name is empty.";
            return false;
        }
    } // end of validate


    public function upload()
    {
        // run validation
        if (!$this->validateInput())
        {
            return $this->result;
        }
        else
        {
            $f_name = $this->fileName;
            $path_fileName = $this->path.$this->fileName;

            if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $path_fileName))
            {
                $this->result[] =
                    "File  ".  basename( $_FILES['uploadedfile']['name']). " was uploaded";
            }
            else
            {
                $this->result[] = "There was an error uploading the file, please try again!";
            }

            $this->result[] = $path_fileName;
            return  $this->result;

        } // end of else : upload execution if no errors
    }

} // end of upload class

[...]

//****************************************/

// call the object
// form here with a if - post ... 
$the_array = $test->upload();
$test = new upload_f();
// assgin values
$test->path = "docs/";
$test->fileName = $_FILES['uploadedfile']['name'];
$the_array = $test->upload();
echo "<pre>";
print_r ($the_array);
echo "</pre>";

You should change validateInput() to:

public function validateInput() {    
    if (empty($this->fileName)) {
        $this->result[] = "ERROR: File name is empty.";
        return false;
    }
    return true; // <-- return true if input is valid
}

As you have it, the method returns something falsy for all cases, causing !$this->validateInput() always to evaluate to true .

Reference

Not sure if it's your problem, but you're missing a closing brace at the end of your upload class.

I noticed looking at your code that you have an odd style of using curly braces. It would be great to get in the habit of picking a style and sticking with it. You can use any style, as long as it's consistent. Here's a list of them: Indent Styles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM