Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

A Walk Through PHP

PHP pages are generally 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!"; ?>
<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) 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 and is currently configured. 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.

Partial output of phpinfo()
Figure 1-3. Partial output of phpinfo()

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.

Example 1-3. Processing a form (form.php)
<html>
  <head>
    <title>Personalized Greeting Form</title>
  </head>

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

    <form action="<?php echo $_SERVER['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 primarily 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 year the book was published, and the book’s ISBN number.

Note

The SQL code for this sample database is in the provided files called library.sql. You can drop this into MySQL after you create the library database, and have the sample database at your disposal for testing out the following code sample as well as the related samples in Chapter 8.

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 while 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 (booklist.php)
<?php

$db = new mysqli("localhost", "petermac", "password", "library");

// make sure the above credentials are correct for your environment
if ($db->connect_error) {
  die("Connect Error ({$db->connect_errno}) {$db->connect_error}");
}

$sql = "SELECT * FROM books WHERE available = 1 ORDER BY title";
$result = $db->query($sql);

?>
<html>
<body>

<table cellSpacing="2" cellPadding="6" align="center" border="1">
  <tr>
    <td colspan="4">
      <h3 align="center">These Books are currently available</h3>
    </td>
  </tr>

  <tr>
    <td align="center">Title</td>
    <td align="center">Year Published</td>
    <td align="center">ISBN</td>
  </tr>
  <?php while ($row = $result->fetch_assoc()) { ?>
    <tr>
      <td><?php echo stripslashes($row['title']); ?></td>
      <td align="center"><?php echo $row['pub_year']; ?></td>
      <td><?php echo $row['ISBN']; ?></td>
    </tr>
  <?php } ?>
</table>

</body>
</html>

Database-provided dynamic content drives the news, blog, and ecommerce 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 (graphic_example.php)
<?php
if (isset($_GET['message'])) {
  // load font and image, calculate width of text
  $font = "times";
  $size = 12;
  $image = 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($image) - $dx) / 2;
  $y = (imagesy($image) - $dy) / 2 + $dy;

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

  // return image
  header("Content-type: image/png");
  imagepng($image);

  exit;
} ?>
<html>
  <head>
    <title>Button Form</title>
  </head>

  <body>
    <form action="<?php echo $_SERVER['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, while Chapter 10 provides instruction on how to create Adobe PDF files.

Button creation form
Figure 1-6. Button creation form
Button created
Figure 1-7. Button created

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 will have mastered PHP!

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required