URL Rewriting

The two functions output_add_rewrite_var() and output_reset_rewrite_vars() cause your URLs, forms, and frames to be rewritten so that they will pass in variables and values of your choosing. They do this by using output buffering and parsing any HTML A elements (links) plus any FORM elements and FRAMES elements and appending fields to URLs contained therein. For example:

    <?php
      output_add_rewrite_var('foo', 'baz');
      echo '<a href="mypage.php">Click here!</A><br />';
      output_add_rewrite_var('bar', 'baz');
      echo '<a href="mypage.php">Click here!</A><br />';

      echo '<form action="mypage.php" method="post">';
      echo '<input type="button" value="  Click here!  " />';
      echo '</form>';
    ?>

    <a href="mypage.php">Click here!</a>

When you run that, you should find that the URLs have been rewritten to point to http://localhost/mypage.php?foo=baz&bar=baz. What's more, both links are the same: the fact that you printed out one link before adding the second variable is irrelevant, thanks to output buffering. The form will have extra hidden fields in there for your values, effectively giving the same result. The best part is that PHP always leaves the forms and URLs working as they did before: any fields in your forms or variables in your URLs will remain there, untouched.

The output_reset_rewrite_vars() function undoes the effects of your calls to output_add_rewrite_var(). One call to output_reset_rewrite_vars() wipes out any variables you've added to URLs and FORMs—it goes back and changes ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.