It can be done in javascript, but not on the server-side directly. You can, however, pass this information to the server by redirecting in one of the two cases with a simple javascript:
if (window.self === window.top) {
// you're not in an iframe
} else {
// in an iframe (or other frames), act accordingly
}
Optionally, if you just want to prevent your site from being viewed in an iframe, you can do this by sending an X-Frame-Options header.