Smart cities have experienced significant growth in recent years, transforming people’s lives into a more futuristic version. The smart city initiative includes a diverse collection of specifications, encompassing a large number of users whose requirements vary significantly and heterogeneously. Each device in smart cities generates a significant amount of data, which places a load on the gateways. Smart cities face a major challenge due to the enormous amount of data they generate. Through software-defined networking (SDN), network information paths are optimized, ensuring that traffic flow is evenly distributed across all network nodes. A considerable number of IoT devices with limited resources are susceptible to various security threats, such as device hijacking, ransomware, man-in-the-middle (MiM) attacks, and distributed denial-of-service (DDoS) attacks. These threats can pose a severe challenge to network security. Additionally, DDoS attacks have disrupted web businesses, resulting in the loss of valuable data. To counter DDoS attacks in a smart city, several options exist, yet many challenges remain. This research presents a secure and intelligent system to combat DDoS attacks on smart cities. SDN security controllers and machine learning models with optimization are employed in this study to reduce the impact of common DDoS attacks on smart cities. This work utilizes an SDN based on security controllers and a detection mechanism rooted in a machine learning model with optimization to mitigate various types of prevalent DDoS attacks within smart cities. Employing binary classification, XGBoost achieved an accuracy of 99.99%, precision of 97%, recall of 99%, an F1 score of 98%, and a false-positive rate of 0.05. In multiclass classification, the average accuracy is 99.29%, precision is 97.7%, recall is 96.69%, and the F1 score is 97.51%. These results highlight the superiority of this approach over other existing machine learning techniques.