Page 247 - Asterisk™: The Future of Telephony
P. 247
return $matches[1];
}
}
else
{
fwrite(STDERR,"FAIL (unexpected result '$res')\n");
fflush(STDERR);
return -1;
}
}
The checkresult function is identical in purpose to the checkresult subroutine we saw
in our Perl example. As its name suggests, it checks the result that Asterisk returns
whenever we call an AGI command.
?>
At the end of the file, we have our closing PHP tag. Don’t place any whitespace after
the closing PHP tag, as it can confuse the AGI interface.
We’ve now covered two different languages in order to demonstrate the similarities
and differences of programming an AGI script in PHP as opposed to Perl. The following
things should be remembered when writing an AGI script in PHP:
• Invoke PHP with the -q switch; it turns off HTML in error messages.
• Turn off the time limit, or set it to a reasonable value (newer versions of PHP
automatically disable the time limit when PHP is invoked from the command line).
• Turn off output buffering with the ob_implicit_flush(false) command.
• Open file handles to STDIN, STDOUT, and STDERR (newer versions of PHP may have
one or more of these file handles already opened; see the previous code for a slick
way of making this work across most versions of PHP).
• Read variables from STDIN using the fgets function.
• Use the fwrite function to write to STDOUT and STDERR.
• Always call the fflush function after writing to either STDOUT or STDERR.
The PHP AGI Library
For advanced AGI programming in PHP, you may want to check out the PHPAGI
project at http://phpagi.sourceforge.net. It was originally written by Matthew Asham
and is being developed by several other members of the Asterisk community.
Writing AGI Scripts in Python
The AGI script we’ll be writing in Python, called “The Subtraction Game,” was inspired
by a Perl program written by Ed Guy and discussed by him at the 2004 AstriCon con-
ference. Ed described his enthusiasm for the power and simplicity of Asterisk when he
Writing AGI Scripts in Python | 219