BOMBOLOM.COM

(webdev) Redirect a web page with PHP

Posted by José Lopes.

Imagine that you have somewhere in your site a quantity of files, with similar information, named after some convention name (like 1000, 1001, etc). Its nice to provide a form where the users my access the files by type the convention name.

A possible solution is to create a form that uses PHP to re-direct the users to the correct file. Using this without any javascript assures that you won't have navigation problems due to javascript not activated.

This post shows how to use a form and PHP to re-direct your users to an existing file (HTML, PDF, etc), based on the value passed on the form.

First we have to create the form, that can be more or less complicated depending on the requirements. Lets assume something simple for example:

<form action="form_handler.php" method="get">
Type in the number: <input name="ref" type="text">
</form>

As you may see:

Now we need the PHP to work the magic. We create the file form_handler.php with the following code:

   <?php
(1)$name = $_GET['ref'];
(2)header("Location: http://YOUR_SITE_ADDRESS_TO_FILES" . $name . ".html");
   ?>

Explaining the code:

(1)We get the input value (name ref) from the form.
(2)We make the forwarding to the file, composing the full path and placing the input value on the correct place.

This is a very straight forward solution and we can change it to fill any needs.

We can have more than one value on the form, for instance two input fields and a PHP file like:

<?php
$name1 = $_GET['ref1'];
$name2 = $_GET['ref2'];
header("Location: http://YOUR_SITE_ADDRESS_TO_FILES" . $name1 . "SOMETHING" . $name2 . ".html");
?>

If we need to make sure that the input value is uppercase we implement that feature on the PHP file:

<?php
$name = $_GET['ref'];
header("Location: http://YOUR_SITE_ADDRESS_TO_FILES" . strtoupper($name) . ".html");
?>

The PHP function strtoupper() converts the string to uppercase. If we need lowercase we can use the function strtolower(). As you can figure out, any other string functions are valid depending of what we want.

You can see an application example here.

2008.01.20 | There's more... | Comments 0 | Tags ,

Deixe a sua mensagem:

Nome:


E-mail:


URL:


Comment:

Secret number

To send you comment you must insert the "secret number" on the box


Made with PyBlosxom | Add to Google