If you could post your code along with details of the error or incorrect behaviour you are experiencing, then someone might be able to help you out. For example, the problem may not be in the code, but in your PHP set up - to quote from the PHP manual's section on image functions:
"You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with."
On the other hand, if you'd rather start from scratch, the generic term for what you are trying to achieve is "CAPTCHA" which stands for "Completely Automated Public Turing test to tell Computers and Humans Apart" - at least that's what wikipedia says.
Here is a Google search for "php captcha" which may find other scripts.
But if your PHP is not configured to handle image manipulation, none of the image functions will work, no matter whose code you use 🙂