Este é um post de José Lopes.
Imagine que no seu site tem uma quantidade razoável de ficheiros, com uma informação similar mas
individual, com um nome segundo uma convenção definida (tipo 100, 1001, etc). Pode ser interessante
facultar uma form onde os utilizadores possam aceder aos ficheiros inserindo o nome convencionado.
Uma solução possível é criar uma form que utiliza PHP para direccionar os utilizadores ao
ficheiro correcto. Uma solução deste tipo que não recorre a javascript assegura que não haja problemas
de navegação (por não estar activado a opção javascript).
Neste post mostro como se pode utilizar uma form e php para redireccionar o
utilizador para uma página estática existente.
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.
A primeira coisa a fazer é escrever a nossa form, que pode ser mais ou menos complicada consuante os nossos
requerimentos. Vamos considerar algo simples como por exemplo:
<form action="form_handler.php" method="get">
Escreva o número: <input name="ref" type="text">
</form>
Como pode verificar:
- A form chama um ficheiro em PHP com o nome form_handler.php.
Notar que neste caso o ficheiro PHP tem o mesmo caminho (path) que o ficheiro de HTML que contém a form.
Se não tivesse teria de ser definido correctamente.
- O método utilizado é o GET uma vez que se está a solicitar informação ao servidor sem alteração da mesma. Para referência
acerca deste método visualize o artigo
Diferença entre GET e POST.
- O input tem um nome que será chamado no ficheiro PHP. Claro que podemos sempre colocar neste input as opções do HTML.
Agora queremos que o PHP faça a sua magia. Criamos o ficheiro form_handler.php com o seguinte código:
<?php
(1)$name = $_GET['ref'];
(2)header("Location: http://O_PATH_PARA_OS_FICHEIROS" . $name . ".html");
?>
Explicando o código:
(1)Obtemos o valor do input ref da form (o nome que colocámos).
(2)Fazemos o encaminhamento para o ficheiro compondo o path completo e com o valor do input no lugar correcto.
Esta é uma solução simples que pode ser adaptada a qualquer necessidade.
Podemos ter mais do que um valor na form, por exemplo dois campos de input e um ficheiro PHP com o código:
<?php
$name1 = $_GET['ref1'];
$name2 = $_GET['ref2'];
header("Location: http://O_PATH_PARA_OS_FICHEIROS" . $name1 . "QUALQUER_COISA" . $name2 . ".html");
?>
Se o valor que recebemos tiver de estar em maiúsculas, podemos implementar esta especificação no ficheiro PHP:
<?php
$name = $_GET['ref'];
header("Location: http://O_PATH_PARA_OS_FICHEIROS" . strtoupper($name) . ".html");
?>
A função de PHP strtoupper() converte uma string em maiúsculas. Se fosse minúsculas o pretendido poderiamos usar a função
strtolower(). Como podem imaginar qualquer função de strings pode ser utilizada consuante o que necessitamos.
Pode ver um exemplo de aplicação desta solução
aqui.
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:
- The form calls the PHP file form_handler.php.
Please note that in this case I assume that the
PHP file has the same path as the HTML file with the form, otherwise it would had to have the correct path.
- The method used is GET since we are demanding information from the server without changing data. For
reference concerning this method
click here.
- The input has a name that will be called on the PHP file. Of course, we can also put on the input valid HTML options.
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.