Kapitel 32. Using PHP

This section gathers most common errors that occur at build time.

1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
2. I need to convert all single-quotes (') to a backslash followed by a single-quote. How can I do this with a regular expression?
3. When I do the following, the output is printed in the wrong order:

      function myfunc($argument) {
        echo $argument + 10;
      }
      $variable = 10;
      echo "myfunc($variable) = " . myfunc($variable);
    
what's going on?
4. Hey, what happened to my newlines?

<PRE>
  1 <?echo $result[1];?>
  2 <?echo $result[2];?>
    
5. I need to access information in the request header directly. How can I do this?
6. When I try to use authentication with IIS I get 'No Input file specified'.
7. I've followed all the instructions, but still can't get PHP and IIS to work together!
8. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.
9. How am I supposed to mix XML and PHP? It complains about my <?xml> tags!
10. How can I use PHP with FrontPage or Dreamweaver or some other HTML editor that insists on moving my code around?
11. Where can I find a complete list of pre-set variables available to me, and why are these not documented in the PHP documentation?
12. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?
13. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. Where are they?
14. How do I get all the results from a SELECT MULTIPLE HTML tag?

1. I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?

Make sure that the track_vars feature is enabled in your php3.ini file. If you compiled PHP with "--enable-track-vars" it will be on by default. Alternatively you can enable it at run-time on a per-script basis by putting <?php_track_vars?> at the top of your file. When track_vars is on, it creates three associative arrays. $HTTP_GET_VARS, $HTTP_POST_VARS and $HTTP_COOKIE_VARS. So, to write a generic script to handle POST method variables you would need something similar to the following:

    while (list($var, $value) = each($HTTP_POST_VARS)) {
        echo "$var = $value<br>\n";
    }
      

2. I need to convert all single-quotes (') to a backslash followed by a single-quote. How can I do this with a regular expression?

First off, take a look at the addslashes()() function. It will do exactly what you want. You should also have a look at the magic_quotes_gpc directive in your php.ini file.

3. When I do the following, the output is printed in the wrong order:

      function myfunc($argument) {
        echo $argument + 10;
      }
      $variable = 10;
      echo "myfunc($variable) = " . myfunc($variable);
    
what's going on?

To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the value, not echo() it.

4. Hey, what happened to my newlines?

<PRE>
  1 <?echo $result[1];?>
  2 <?echo $result[2];?>
    

In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). This means that you need to insert an extra newline after each block of PHP code in the above example.

Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.

5. I need to access information in the request header directly. How can I do this?

The getallheaders() function will do this if you are running PHP as a module. So, the following bit of code will show you all the request headers:

    $headers = getallheaders();
    for(reset($headers); $key = key($headers); next($headers)) {
        echo "headers[$key] = ".$headers[$key]."<br>\n";
    }
     

6. When I try to use authentication with IIS I get 'No Input file specified'.

The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by php) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. When the ISAPI module is ready, this will no longer be a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/support/kb/articles/q160/4/22.asp.

7. I've followed all the instructions, but still can't get PHP and IIS to work together!

Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine.

8. My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape.

Very good question! ;) This is a tricky little issue and it has come up twice in the past month as of this writing. Both times I ended up spending a good 20 minutes trying to figure out what the heck was going on. The answer is that both IE and Lynx ignore any NULs (\0) in the HTML stream. Netscape does not. The best way to check for this is to compile the command-line version of PHP (also known as the CGI version) and run your script from the command line and pipe it through 'od -c' and look for any \0 characters. (If you are on Windows you need to find an editor or some other program that lets you look at binary files) When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will. If this issue has bitten you, congratulations! You are not alone.

9. How am I supposed to mix XML and PHP? It complains about my <?xml> tags!

You need to turn off the short tags by setting short_tags to 0 in your php.ini file, or by using the php3_short_tags Apache directive. (You could even use a <File> section to do this selectively.) You can also disable and re-enable the short tags in your script using the short_tags() function.

10. How can I use PHP with FrontPage or Dreamweaver or some other HTML editor that insists on moving my code around?

One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Most of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php.ini variable, or use the asp_tags Apache directive.

11. Where can I find a complete list of pre-set variables available to me, and why are these not documented in the PHP documentation?

The best way is to stick a <?phpinfo()?> tag on a page and load it up. This will show you all sorts of information about your PHP setup, including a list of both environment variables and also special variables set by your web server. This list can't really be documented in the PHP documentation because it will change from one server to another.

12. Why do I get an error that looks something like this: "Warning: 0 is not a MySQL result index in <file> on line <x>" or "Warning: Supplied argument is not a valid MySQL result resource in <file> on line <x>?

You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:

        $result = mysql_query("select * from tables_priv");
        if(!$result) {
            echo mysql_error();
            exit;
        }
      
or

        $result = mysql_query("select * from tables_priv")
                    or die("Bad query: ".mysql_error());
      

13. I'm trying to use an <input type="image"> tag, but the $foo.x and $foo.y variables aren't available. Where are they?

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

<input type="image" SRC="image.gif" NAME="foo">
      
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.

Because $foo.x and $foo.y are invalid variable names in PHP, they are automagically converted to $foo_x and $foo_y. That is, the periods are replaced with underscores.

14. How do I get all the results from a SELECT MULTIPLE HTML tag?

The SELECT MULTIPLE tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. ie.

      <SELECT NAME="var" MULTIPLE>
      
Each selected option will arrive at the action handler as:

   var=option1
   var=option2
   var=option3
      
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's non-indexed array feature. The following should be used:

<SELECT NAME="var[]" MULTIPLE>
      
This tells PHP to treat var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[0], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.

Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element id instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:

variable = documents.forms[0].elements['var[]'];