CSE 154

Lecture 19: Creating a PHP API

Review: Web Services

Web service: software functionality that can be invoked through the internet using common protocols

A remote function(s) you can call by contacting a program on a web server

Many web services accept parameters and produce results

Can be written in PHP and contacted by the browser in HTML and/or AJAX code

The service's output might be HTML but could be text, XML, JSON, or other content

Setting Content Type with header


          header("Content-type: type/subtype");
            

PHP (template)


          header("Content-type: type/plain");
          print "This output will appear as plain text now!\n";
            

PHP (example)

By default, a PHP file's output is assumed to be HTML (text/html)

However, in this course we aren't using PHP to generate HTML, so we use the header function to specify non-HTML output

  • Must appear before any other output generated by the script
  • The header call doesn't have to be the first line of code
  • A good write up on HTTP Headers and PHP header

Recall: Content ("MIME") Types

MIME type file extension
text/html .html
text/plain .txt
image/gif .gif
image/jpeg .jpg
video/quicktime .mov
application/octet-stream .exe

List of MIME types

Example: Exponent Web Service

Write a web service that accepts a base and exponent and outputs base to the exponent power. For example, the following query should output 8:


          http://example.com/exponent.php?base=2&exponent=3
            

Solution


<?php
  header("Content-type: text/plain"); // return as plain text
  $base = (int) $_GET["base"];
  $exp = (int) $_GET["exponent"];
  $result = pow($base, $exp);
  print $result;
?>
            

PHP

Try creating an exponent.php file with this in it. Call this php file from your server with the appropriate parameters and see what the result is.

HTML error codes with PHP


<?php
if ((isset($_GET["base"]) && !is_numeric($_GET["base"])) ||
  (isset($_GET["exponent"]) && !is_numeric($_GET["exponent"]))) {
    header("HTTP/1.1 400 Invalid Request");
    header("Content-type: text/plain");
    print("Parameters must be numerical values")
  }
  else {
    ...
  }
?>
					

PHP

  • Default 200 (status OK) header is set by default.
  • To set a non 200 (status OK), use the header function.
  • In case of an error, you may need two calls to the header function, once to set the error code, and the second time to set the Content-Type.

Obtrusive (Embedded) PHP

We are focused on PHP for data generation!

We are showing you this strictly for historical purposes

  • You will likely see this in code others have produced
  • The optional textbook for this class discusses this method

The next slides are for informational purposes only

Embedded PHP Syntax Template


          HTML content
          <?php
             PHP code
          ?>

          HTML content
          <?php
             PHP code
          ?>

          HTML content...
          

HTML/PHP (template)

Any contents of a .php file between <?php and ?> are executed as PHP code

All other contents are output as pure HTML

PHP Expression Blocks (Embedded PHP)


<DOCTYPE html>
<html>
  <head><title>CSE 154: Embedded PHP</title></head>
  <body>
  <?php for ($i = 99; $i >= 1; $i--) { ?>
    <p> <?= $i ?> bottles of beer on the wall, <br />
  <?= $i ?> bottles of beer. <br />
    Take one down, pass it around, <br />
  <?= $i - 1 ?> bottles of beer on the wall. </p>
  <?php } ?>
  </body>
</html>

          

PHP

This is messy! There are much better ways to do this, and you should not write any embedded PHP in this class. But you should be aware of it.

PHP File I/O

PHP I/O Functions

function name(s) category
file, file_get_contents, file_put_contents reading/writing entire files
basename, file_exists, filesize, fileperms, filemtime, is_dir, is_readable, is_writable, disk_free_space asking for information
copy, rename, unlink, chmod, chgrp, chown, mkdir, rmdir manipulating files and directories
glob, scandir reading directories

PHP: Reading from Directories

Reading Directories

function description
glob returns an array of all file names that match a given pattern (returns a file path and name, such as "foo/bar/myfile.txt")
scandir returns an array of all file names in a given directory (returns just the file names, such as "myfile.txt")

Can accept a general path with the * wildcard (more powerful).

glob Example


          $ducks = glob("ducks/*");
          

PHP


Array
(
  [0] => ducks/B-duck
  [1] => ducks/D-duck
	...
  [11] => ducks/X-duck
  [12] => ducks/Z-duck
)
          

result

glob can match a wildcard path with the * character

  • glob("foo/bar/*.doc") returns all .doc files in the foo/bar subdirectory
  • glob("food*") returns all files whose names begin with "food"

The basename function strips any leading directory from a file path

  • basename("ducks/B-duck") returns "B-duck"

scandir Example


          $ducks = glob("ducks/*");
          

PHP


Array
(
  [0] => .
  [1] => ..
  [2] => B-duck
  [3] => D-duck
	...
  [13] => X-duck
  [14] => Z-duck
)
          

result

scandir includes current directory (".") and parent ("..") in the array.

Don't need basename with scandir; returns file names only without directory

Reading/Writing Files

contents of foo.txt file("foo.txt") file_get_contents("foo.txt")
Hello
how r u?

I'm fine

                
array("Hello\n", #0
"how r u?\n",    #1
"\n",            #2
"I'm fine\n"     #3
)
                
"Hello\n
how r u\n    # a single
\n           # string
I'm fine\n"
                

The file function returns lines of a file as an array (\n at end of each).

file_get_contents returns entire contents of a file as a single string.

file_put_contents writes a string into a file.

The file Function


          # display lines of file as a bulleted list
          $lines = file("todolist.txt");
          foreach ($lines as $line) { # for ($i = 0; $i < count($lines); $i++)
            print $line;
          }
          

PHP

file returns the lines of a file as an array of strings.

Each ends with \n; to strip it, use an optional second parameter:


          $lines = file("todolist.txt", FILE_IGNORE_NEW_LINES);
          

PHP

Common idiom: foreach or for loop over lines of file

Reading/Writing an Entire File


          # reverse a file
          $text = file_get_contents("poem.txt");
          $text = strrev($text);
          file_put_contents("poem.txt", $text);
          

PHP

file_get_contents returns entire contents of a file as a string

  • if the file doesn't exist, you will get a warning and an empty return string

file_put_contents writes a string into a file, replacing its old contents

  • if the file doesn't exist, it will be created

Example


          # reverse all poems in the poetry directory
          $poems = glob("poetry/poem*.dat");
          foreach ($poems as $poemfile) {
            $text = file_get_contents($poemfile);
            file_put_contents($poemfile, strrev($text));
            print "I just reversed " . basename($poemfile) . "\n";
          }
          

PHP

Appending to a File


          # add a new line to a file
          $new_text = "P.S. ILY, GTG TTYL!~";
          file_put_contents("poem.txt", $new_text, FILE_APPEND);
          

PHP

old contents new contents
Roses are red
Violets are blue
All my base
Are belong to you.
Roses are red
Violets are blue
All my base
Are belong to you.
P.S. ILY, GTG TTYL!~

file_put_contents can be called with an optional third parameter to append (add to end) rather than overwrite.