|How to call an external script and get the error message (if any)?|
...and should I be using do(), system(), backticks?
My web application has various *cgi files which call 'authenticate.pl' to make sure the user should really be able to execute the file. I've been calling that script with do('authenticate.pl'), but I just discovered that if an open() command in that script fails, the or die... part doesn't get written to the web browser. (Yes, I printed the content header.)
So do I need to do something special to make sure the error prints, or should I be using some other way of calling the authentication script in the first place, such as system() or backticks? I thought do was a "cleaner" way of calling external scripts (best practices, because less possibility of security issues), so that's why I started with that. But I'll switch if that's the best way to do it.
If you just want the error messages to be printed to the browser, you might succeede with putting
use CGI::Carp qw(fatalsToBrowser);
in your original scripts.
"do" will run the perl code, but not in an external process, which system() or backtics will. If you switch to that, you'll have to catch errors from the authentication script and work with them to find out if auth is fine. Also, you can't read and set variables of your script.
I'd stick with "do" (or "require"), but handle it a bit cleaner, make the authentication a sub routine that returns status (1 = authed, 0 = failed) and an optional message that indicated why authentication failed. Then handle that however you want to (show public data only, print the message and exit, insult the user or whatever)
If you want to call the authenticate.pl script but not halt all processing of the calling CGI, you could put the do('authenticate.pl') call in an eval block. Depending on what you are reading/doing with authenticate.pl, this might not be safe enough, but it will let you safely catch and then parse, display, etc. any 'die' errors thrown from authenticate.pl.
Alternatively, I would consider doing something similar to what janharders suggested and set things up so you can just set error codes or flags from an authentication routine and display appropriate messages to those that should see them. Die'ing in a CGI can get kind of messy very quickly ;)