0
if(isset($_POST['submit'])&& isset($_FILES['file'])){
    $Uploads = new Uploads($_FILES);
    $Uploads->UploadLocation = "../images/categories/";
    if($Uploads->isValidated()== TRUE){
    $Image = array("image" => $Uploads->upload());
    $_POST = array_merge($_POST,$Image);
    unset($_POST['submit']);
    $Category = new Categories();
    $Category->insertCategory("users", $_POST);
    }
    else {
        print_r($Uploads->isValidated());   
    }
}
?>

if ステートメントを$Uploads->isValidated()関数の前に置いたので、残りのコードは true が返されたときにのみ実行されます。以下は関数コードです。

public function isValidated(){
        if($this->containsError() && $this->isValidFile() && $this->isValidSize()){
            return TRUE;
        }
        else
        {
            return $this->ValidationMessages;
        }
    }

メソッドが TRUE を返すよりも、3 つのメソッドすべてが TRUE を返すかどうかを確認しましたisValidated()。これ$this->ValidationMessagesは、3 つの検証メソッドのいずれかが TRUE を返さない場合に埋められるメッセージの配列です。

エラーメッセージが表示されているかどうかを確認するために、意図的にこのクラスにファイルを渡さないようにしていますが、残りのコードをまだ実行しているため、isValidated() メソッドが TRUE を返す必要はありません。

私の3つの検証方法はすべてチェックしたので完璧に機能していることに注意してください。そのため、ここに投稿していません。しかし、必要に応じてコードを投稿できます。

検証メッセージが表示されない理由を理解するのに助けが必要です。

更新部分:

private function containsError(){
        //checking if file contains any error
        if(!empty($this->FileError)){
            $this->ValidationMessages[] = "Sorry, This file contains error";
        }
        else {
            return TRUE;
        }     
    }

   private function isValidFile() {
        // putting the allowed files in array
        $AllowedExt = array('jpg', 'jpeg', 'gif', 'png');
        // matching with allowed file types
        if (in_array($this->FileExt, $AllowedExt)) {
            return TRUE;
        } else {
            $this->ValidationMessages[] = "This extension is not allowed";
            return FALSE;
        }
    }

private function isValidSize() {
    // setting the maximum size limit in bytes
    $AllowedSize = 1048576;
    // checking if the user file does not exceed the allowed size
    if (!$this->FileSize < $AllowedSize) {
        return TRUE;
    } else {
        $this->ValidationMessages[] = "File should not be greater than 1MB";
        return FALSE;
    }
}
4

1 に答える 1