I'm a bit stumped at how you solved the problem of people being able to access the .txt files and read the captcha as text. Including a temporary .php file - even worse, with a name generated from input of the website user - to set a variable is kind of dangerous.
The typical programming pattern in such a case would be to still save into the .txt file, but save two values: first n characters a salt, i.e. a string containing random alphabet/number chars, next 64 characters a hash of the captcha string concatenated with the salt.
So when you want to check the correctness of $input, you load the .txt file content to a string, extract the first n characters to $salt, and check hash('sha256', $input . $salt) against the last 64 characters of the string. (If you're not familiar with the technique, look for hash function and cryptographic salt at wikipedia.)
That would be alot safer than what you're doing now.