To provide remote access, surveillance, and analysis, network integration is common in Cyber-Physical Systems (CPSs). This leads to cyber attacks due to the integration of insecure networking devices. In violating internet security, the attackers interfere with system function, which leads to shattering consequences. With the incorporation of Fog with IoT, the attacks in the CPS can be detected in less time than in cloud-based CPS. The detection of attacks on CPS is targeted by cybercriminals which increases the identification difficulty. This paper proposes a new swarm-based feature selection algorithm to improve attack detection in an IoT-based CPS environment. An Enhanced Chicken swarm optimization (ECSO) with self-learning ability-based feature selection is used to select the relevant features from the preprocessed data. Next, the ensemble classifiers are executed with the desired features on the cloud. The proposed ECSO-based ensemble classifier has experimented against the NSL-KDD dataset. The evaluated results show the adequate performance of the proposed system using various statistical measures.