URL rewriting

bool output_add_rewrite_var ( string name, string value)

bool output_reset_rewrite_vars ( void )

Once or twice so far we've looked at functions where I've said something like, "you might not realise it now, but this is a really useful function and it will grow on you." These two functions are, uniquely, quite the reverse: they appear incredibly useful on the surface, but it's actually quite hard to find working examples of them in action. That's not to say they are useless: far from it! You will know when you need these functions. Of course, you can't know you need them if you don't know they exist, which is why they are here!

What they do is cause your URLs, forms, and frames to be rewritten so that they will pass in variables and values of your choosing. It does 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. This is best demonstrated with some code, so here goes:

Now, when you run that you should find that the URLs have been rewritten to point to "http://localhost/foo.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 actually 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.

Now, what the output_reset_rewrite_vars() function does is undo 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 them all to be without the added variables.

Here's the same script again, except this time with output_reset_rewrite_vars() tacked on the end:

That will print out all URLs and the form as written, without the "foo" and "bar" variables.

Now, as you can see, using these two seems like a great way to transfer data around your site. Question is, why would you want to? I won't tell you these functions aren't ever used, because I'm sure there are legitimate reasons that are so obscure I can't think of them! Still, it's best you at least know these guys exist.

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!