When used to output HTML content, PHP is embedded inside HTML in code islands, as opposed to in Perl, where HTML code is embedded inside the Perl script. The most common way to open and close PHP code blocks is by <?php and ?>. Here is an example of a simple page, shown in Perl first then in PHP - don't worry about what the code means for now:
#!/usr/bin/perl print "<html>\n"; print "<body>\n"; print "<p>Welcome, $Name</p>\n"; print "</body>\n"; print "</html>\n";
And now in PHP:
<html> <body> <p>Welcome, <?php print $Name; ?></p> </body> </html>
As you can see, the PHP version is only a line shorter, but infinitely much easier to read because the majority of the page is just HTML. Some modules for Perl (particularly CGI.pm) help, but PHP continues to have a big lead in terms of readability. If you really wanted, you could write your PHP script like the Perl script: switch to PHP mode and print everything out from there. However, it tends to get messy - as you can see!
Apart from editing legibility, another advantage to having most of the page in straight HTML is that it makes editing with commercial IDEs possible, whereas products like Dreamweaver trash Perl's print statements.
One key advantage to using PHP as opposed to some other solutions is that PHP code is all executed at the server, with the client only receiving the results of the script. What this means is that users never see your PHP source code because they are never sent it - they only see what you want them to see.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Interpreting vs. Compiling >>
Previous chapter: Advantages of PHP
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.