O'Reilly logo

Programming PHP, 2nd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Walk Through PHP

PHP pages are HTML pages with PHP commands embedded in them. This is in contrast to many other dynamic web-page solutions which are scripts that generate HTML. The web server processes the PHP commands and sends their output (and any HTML from the file) to the browser. Example 1-1 shows a complete PHP page.

Example 1-1. Hello_world.php

<html>
  <head>
    <title>Look Out World</title>
  </head>

  <body>
    <?php echo 'Hello, world!' ?>
  </body>
</html>

Save the contents of Example 1-1 to a file, hello_world.php, and point your browser to it. The results appear in Figure 1-2.

Output of hello_world.php

Figure 1-2. Output of hello_world.php

The PHP echo command produces output (the string "Hello, world!" in this case), which is inserted into the HTML file. In this example, the PHP code is placed between the <?php and ?> tags. There are other ways to tag your PHP code—see Chapter 2 for a full description.

Configuration Page

The PHP function phpinfo( ) creates an HTML page full of information on how PHP was installed. You can use it to see whether you have particular extensions installed, or whether the php.ini file has been customized. Example 1-2 is a complete page that displays the phpinfo( ) page.

Example 1-2. Using phpinfo( )

<?php phpinfo(  ); ?>

Figure 1-3 shows the first part of the output of Example 1-2.

Forms

Example 1-3 creates and processes a form. When the user submits the form, the information typed into the name field is sent back to this page. The PHP code tests for a name field and displays a greeting if it finds one.

Partial output of phpinfo( )

Figure 1-3. Partial output of phpinfo( )

Example 1-3. Processing a form

<html>
  <head>
    <title>Personalized Hello World</title>
  </head>

  <body>
    <?php if(!empty($_POST['name'])) {
      echo "Greetings, {$_POST['name']}, and welcome.";
    } ?>

    <form action="<?php $PHP_SELF; ?>" method="post">
      Enter your name: <input type="text" name="name" />
      <input type="submit" />
    </form>
  </body>
</html>

The form and the message are shown in Figure 1-4.

Form and greeting page

Figure 1-4. Form and greeting page

PHP programs access form values through the $_POST and $_GET array variables. Chapter 7 discusses forms and form processing in more detail. For now be sure that you are processing your pages with the REGISTER_GLOBALS value set to off (the default) in the php.ini file.

Databases

PHP supports all the popular database systems, including MySQL, PostgreSQL, Oracle, Sybase, SQLite, and ODBC-compliant databases . Figure 1-5 shows part of a MySQL database query run through a PHP script showing the results of a book search on a book review site. This is showing the book title, the category of the book, the publisher of that book and the books' ISBN number.

The code in Example 1-4 connects to the database, issues a query to retrieve all available books (with the WHERE clause), and produces a table as output for all returned results through a for next loop.

A MySQL Book list query run through a PHP script

Figure 1-5. A MySQL Book list query run through a PHP script

Example 1-4. Querying the Books database

<?
$connection = mysql_connect("localhost");
$db = "library";
mysql_select_db($db, $connection) or die( "Could not open $db");

$sql = "SELECT * FROM books WHERE available = 1 ORDER BY title";

$result = mysql_query($sql, $connection) or die( "Could not execut sql: $sql");
$num_result = mysql_num_rows($result);

?>

<table cellSpacing="2" cellPadding="6" align="center" border="1">

  <tr>
    <td colspan="7">
      <h3 align="center">These Books are currently available</h3>
    </td>
  </tr>

  <tr>
    <td align="center">Title</td>
    <td align="center">Publisher</td>
    <td align="center">Category</td>
    <td align="center">ISBN</td>
  </tr>
<?
for ($i=0; $i < $num_result; $i++) {

    $row = mysql_fetch_array($result);
    $id = $row["bookid"];

    echo "<tr>";
      echo "<td>";
      echo stripslashes($row["title"]);
      echo "</td><td>";
      if ( !$row["company"] )
            {
          echo "&nbsp;";
          } else {
          echo $row["company"];
      }
      echo "</td><td>";
      echo $row["typedesc"];
      echo "</td><td>";
      echo $row["isbn"];
      echo "</td>";
    echo "</tr>";
}

?>
</table>


</body>
</html>

Database-provided dynamic content drives the news and e-commerce sites at the heart of the Web. More details on accessing databases from PHP are given in Chapter 8.

Graphics

With PHP, you can easily create and manipulate images using the GD extension. Example 1-5 provides a text-entry field that lets the user specify the text for a button. It takes an empty button image file, and on it centers the text passed as the GET parameter "message." The result is then sent back to the browser as a PNG image.

Example 1-5. Dynamic buttons

<?php
 if (isset($_GET['message'])) {
   // load font and image, calculate width of text
   $font = 'times';
   $size = 12;
   $im = ImageCreateFromPNG('button.png');
   $tsize = imagettfbbox($size,0,$font,$_GET['message']);

   // center
   $dx = abs($tsize[2]-$tsize[0]);
   $dy = abs($tsize[5]-$tsize[3]);
   $x = ( imagesx($im) - $dx ) / 2;
   $y = ( imagesy($im) - $dy ) / 2 + $dy;

   // draw text
   $black = ImageColorAllocate($im,0,0,0);
   ImageTTFText($im, $size, 0, $x, $y, $black, $font, $_GET['message']);

   // return image
   header('Content-type: image/png');
   ImagePNG($im);
   exit;
 }
?>
<html>
  <head><title>Button Form</title></head>
  <body>

    <form action="<?= $PHP_SELF ?>" method="GET">
      Enter message to appear on button:
      <input type="text" name="message" /><br />
      <input type="submit" value="Create Button" />
    </form>

  </body>
</html>

The form generated by Example 1-5 is shown in Figure 1-6. The button created is shown in Figure 1-7.

You can use GD to dynamically resize images, produce graphs, and much more. PHP also has several extensions to generate documents in Adobe's popular PDF format. Chapter 9 covers dynamic image generation in depth, and Chapter 10 shows how to create Adobe PDF files.

Button created

Figure 1-6. Button created

Button creation form

Figure 1-7. Button creation form

From the Shell

If you compile PHP without specifying a specific web server type, you get a PHP interpreter as a program instead of a web server module. This lets you write PHP scripts that use PHP functionality such as databases and graphics and yet are callable from the command line.

For example, Example 1-6 also creates buttons. However, it is run from the command line, not from a web server. The -q option to the php executable inhibits the generation of HTTP headers.

Example 1-6. Shell-based PHP program to create a button

#!/usr/local/bin/php -q
<?php
 if ($argc != 3) {
   die("usage: button-cli filename message\n");
 }

 list(, $filename, $message) = $argv;

 // load font and image, calculate width of text
 $font = 'Arial.ttf';
 $size = 12;
 $im = ImageCreateFromPNG('button.png');
 $tsize = imagettfbbox($size,0,$font,$message);

 // center
 $dx = abs($tsize[2]-$tsize[0]);
 $dy = abs($tsize[5]-$tsize[3]);
 $x = ( imagesx($im) - $dx ) / 2;
 $y = ( imagesy($im) - $dy ) / 2 + $dy;

 // draw text
 $black = ImageColorAllocate($im,0,0,0);
 ImageTTFText($im, $size, 0, $x, $y, $black, $font, $message);

 // return image
 ImagePNG($im, $filename);
?>

Save Example 1-6 to button-cli and run it:

    # ./button-cli
    usage: button-cli filename message
    # ./button-cli php-button.png "PHP Button"
    # ls -l php-button.png
    -rwxr-xr-x  1 gnat  gnat  1837 Jan 21 22:17 php-button.png

Now that you've had a taste of what is possible with PHP, you are ready to learn how to program in PHP. We start with the basic structure of the language, with special focus given to user-defined functions, string manipulation, and object-oriented programming. Then we move to specific application areas such as the Web, databases, graphics, XML, and security. We finish with quick references to the built-in functions and extensions. Master these chapters, and you've mastered PHP!

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required