By the time you're ready to print the redirect, you've already printed an HTTP header at the top of the script:
print $query->header;
You need to determine whether you're displaying the form or doing a redirect before you print anything. Do the parameter check first, then print the redirect if every checks out, or print the form otherwise.