I’d say this question is mostly off-topic since it’s not WordPress-specific. Mostly, because the majority of PHP solutions out there use sessions, which will not work out-of-the-box in WordPress.
Google search actually handles this question quite well. Have a look at this discussion for nice techniques.
Finally, Contact Form 7 has Captcha built-in.