A first line of defence of any web application should be a Web Application Firewall (WAF) which will hopefully detect and block malicious behaviour before it can even reach the application.
If the attacker gets past the firewall the next step is typically to modify the application files or add additional files to be executed. You can combat this by using a read-only filesystem, meaning any such attempt to modify or add files to the application are blocked at the operating system level.
In the places where it’s not possible to have a read-only filesystem (media uploads) you can explicitly deny any of those files from being run.
If somehow, malicious code does make its way on to the system you need to be able to detect it. We do this by comparing known (safe) states of the filesystem with the current and any differences are immediately noticeable.