PHP e HTML

PHP e HTML possuem muita interação: PHP pode gerar HTML, e o HTML pode passar informações para o PHP. Antes de ler esses faqs, é importante que você aprenda como recuperar variáveis de fontes externas. A página do manual neste tópico inclui muitos exemplos.

Que codificação/decodificação é preciso quando eu passo um valor através de um formulário/URL?

Existem muitos estágios para o qual a codificação é importante. Assumindo que você tenha uma string $data, o qual contém a string que você quer passar de um jeito não codificado, esses são os estágios relevantes:

  • Interpretação HTML. A fim de especificar uma string aleatória, você precisa incluá-la entre aspas, e converter todo o valor dos caracteres especiais para a realidade HTML usando htmlspecialchars().

  • URL: Uma URL consite de diversas partes. Se você quer que seus dados sejam interpretados como um item, você precisa codificá-los com urlencode().

Exemplo #1 Um elemento oculto de formulário HTML

<?php
    
echo "<input type='hidden' value='" htmlspecialchars($data) . "' />\n";
?>

Nota: É errado urlencode() $data, porque é a responsabilidade do navegador em urlencode() os dados. Todos os navegadores populares o fazem isso corretamente. Note que isso irá acontecer independentemente do método (i.e., GET ou POST).Você só vai perceber isso em caso de solicitação GET, porque as requisições POST são normalmente escondidas.

Exemplo #2 Dados a serem editados pelo usuário

<?php
    
echo "<textarea name='mydata'>\n";
    echo 
htmlspecialchars($data)."\n";
    echo 
"</textarea>";
?>

Nota: Os dados são mostrados no navegador como pretendido, porque o navegador irá interpretar os simbolos de escape do HTML. Em consequência do envio, tando via GET como POST, os dados vão ser urlencoded pelo navegador para transferência, e urldecoded diretamente pelo PHP. Resumindo, você não precisa fazer qualquer urlencoded/urldecoded pelo php, tudo é feito automaticamente.

Exemplo #3 Em uma URL

<?php
    
echo "<a href='" htmlspecialchars("/nextpage.php?stage=23&data=" .
        
urlencode($data)) . "'>\n";
?>

Nota: De fato você está fingindo uma requisição HTML GET, portanto é necessário urlencode() os dados manualmete.

Nota: Você precisa htmlspecialchars() toda a URL, porque a URL ocorre como um valor de um atributo-HTML. Neste caso, o navegador irá primeiramente un-htmlspecialchars() o valor, e então passar a URL. O PHP vai entender a URL corretamente, porque você urlencoded() os dados. Você vai notar que & na URL é substituido por &amp;. Embora a maioria dos navegadores vão se recuperar se vecê esquecer disto, isso nem sempre é possivel. Então, memso se a URL não é dinâmica, você precisa htmlspecialchars() a URL.

Estou tentando usar uma tag <input type="image">, mas as variáveis $foo.x e $foo.y não estão disponíveis. $_GET['foo.x'] não existem também. Onde elas estão?

Ao enviar um formulário, é possivel usar uma imagem em vez de um botão submit padrão, como na tag:

<input type="image" src="image.gif" name="foo" />
Quando o usuário clica em qualquer lugar na imagem, o formulário que o acompanha será transmitido para o servidor com duas variáveis adicionais: foo.x e foo.y.

Porque foo.x e foo.y faria nome de variáveis inválidas no PHP, elas são automaticamente convertidas para foo_x e foo_y. Ou seja, os periodos são substituidos por sublinhados. Então, você teria acesso a essas variáveis como qualquer outro descrito na seção sobre como recuperar variáveis de fontes externas. Por exemplo, $_GET['foo_x'].

Nota:

Os espaços nos nomes das variáveis requisitadas são convertidas para sublinhado.

Como eu crio arrays em um HTML <form>?

Para obter o resultado do seu <form> enviado como um array para seu script PHP você nomeia os elementos <input>, <select> ou <textarea> como estes:

<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyArray[]" />
Observe os colchetes após o nome da variável, é isso que torna uma variável um array. Você pode agrupar os elementos dentro de diferentes arrays, atribuindo o mesmo nome a diferentes elementos:
<input name="MyArray[]" />
<input name="MyArray[]" />
<input name="MyOtherArray[]" />
<input name="MyOtherArray[]" />
Isso poduz dois arrays, MyArray e MyOtherArray, que serão enviados para o script PHP. Também é possível atribuir chaves específicas para seus arrays:
<input name="AnotherArray[]" />
<input name="AnotherArray[]" />
<input name="AnotherArray[email]" />
<input name="AnotherArray[phone]" />
O array AnotherArray ira conter agora as chaves 0, 1, email e phone.

Nota:

Especificar uma chave de array é opcional no HTML. Se você não especificar as chves, o array preenche na ordem em que os elementos aparecem no formulário. Nosso primeiro exemplo ira conter as chaves 0, 1, 2 e 3.

Veja também: Funções de Array e Variáveis de fontes Externas.

Como eu faço para obeter os resultados de uma múltipla seleção de uma tag HTML?

A seleção de multiplas tags em uma construção HTML permite os usuários selecionar multiplos itens de uma lista. Esses itens são então passados ao manipilador de ações para o formulário. O problema é que eles são todos passados com o mesmo nome widget. I.e.

<select name="var" multiple="yes">
Cada opção selecionada chegará ao manipulador de ações como:
var=option1
var=option2
var=option3
      
Cada opção irá substituir o conteúdo da variável anterior $var. A solução é usar a caracteristica "array de elementos do formulário" do PHP. A seguir devem ser usados:
<select name="var[]" multiple="yes">
Isso diz ao PHP para tratar $var como um array e cada atribuição de um valor para [var] acrescenta um item ao array. O primeiro item se torna $var[0], o próximo $var[1], etc. A função count() pode ser chamado para determinar quantas opções foram selecionadas, e a função sort() pode ser usada para classificar o array de opções se necessário.

Note que se você esta usando JavaScript o [] no nome do elemento pode lhe causar problemas quando você tenta se referir ao elemento pelo nome. Ao invés use o ID numérico do elemento do formulário, ou coloque o nome da variável entre aspas simples e use isso como um índice para os elementos do array, por exemplo:

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

Como eu posso passar uma variável do Javascript para o PHP?

Uma vez que o Javascript é (normalmente) uma tecnologia da parte do cliente, e o PHP é (normalmente) uma tecnologia da parte do servidor, e uma vez que o HTTP é um protocolo "sem lado", as duas linguagens não podem compartilhar variáveis diretamente.

É , no entanto, possível passar variáveis entre as duas. Uma maneira de realizar isso é gerar um código Javascript com PHP, e ter um navegador que se atualize, passando variáveis especificas de volta para o script PHP. O exemplo abaixo mostra precisamente como fazer isso -- isso permite ao código PHP capturar a altura e largura da tela, algo que normalmente só é possível no lado do cliente.

Exemplo #4 Gerando Javascript com PHP

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  
// output the geometry variables
  
echo "Screen width is: "$_GET['width'] ."<br />\n";
  echo 
"Screen height is: "$_GET['height'] ."<br />\n";
} else {
  
// pass the geometry variables
  // (preserve the original query string
  //   -- post variables will need to handled differently)

  
echo "<script language='javascript'>\n";
  echo 
"  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            
"&width=\" + screen.width + \"&height=\" + screen.height;\n";
  echo 
"</script>\n";
  exit();
}
?>

add a note add a note

User Contributed Notes 7 notes

up
-1
murphy
4 years ago
The scenario:

1. There is a php script which (possibly complemented by a direct written HTML code) consrtucts a HTML page via its echo command, based on whatever algoritmus eventually based on supplementary data from server files or databases.

2. This php script leads to data being saved into string variable(s), which (possibly) can contain arbitrary characters, including control codes (newline, tab...), HTML special characters (&,<...) and non-ASCII (international) characters.

3. These non-ASCII characters are UTF-8 encoded, as well as the HTML page (I do highly recommend) *)

4. The values of these PHP string variables have to be transferred into javascript variables for further processing by javascript (or exposing these values in HTML directly)

The problem:

it is not safe to PHP-echo such variables into HTML (javascript) directly, because some of characters possily contained in them cause malfunction of the HTML. These strings need some encoding/escaping in order to become strings of non-conflicting characters

The solution

There may be a big lot of ways of this encoding. The following one seems to me the easiest one:
The PHP variable with unpredictable value can originate from some file, as an example (or from user input as well):

$variable=file_get_content(...)

1. Convert all bytes of that string into hex values and prepend all hex-digit-pairs with %

$variable_e=preg_replace("/(..)/","%$1",bin2hex($variable))

The new variable is now guarantied to contain only %1234567890abcdefABCDEF chracters (e.g. %61%63%0a...) and can safely be directly echoed into HTML:

var variable="<?php echo $variable_e;?>" //that's NOT all folks

But now the value is still encoded. To get the original value of the variable, it has te be decoded: *)

var variable=decodeURIComponent("<?php echo $variable_e;?>")

The value of the variable is now the same as the original value.

*) I have no idea about non-UTF-8 encoded pages/data, espetially how the decodeURIComponent works in such a case, because i have no reason to use other encodings and handle them as highly deprecatad.

WARNING: this approach is not (generally) safe against code injection. I highly recommend some further check (parsing) of the value depending on the particular case.

P.S. For very large amount of data, I would recomment to save them into file on the PHP side (file_put_content) and read them by javascript via HTTP Request.

I use this approach as it needs one line of code on server as well as client side. I do agree with arguement that not all chaeacters have to be encoded.

Do not enjoy my possibly stupid solution, if you have a better idea

murphy
up
-18
smileytechguy at smileytechguy dot com
6 years ago
The (at least that I've found) best way to pass data from PHP to JS is json_encode.  Doing so will convert arrays, strings, numbers, etc. as best as possible.

<?php
$myInt
= 7;
// a bunch of special characters to demonstrate proper encoding
$myString = <<<EOF
" ' ; &\ $
EOF;
$myArr = [1, "str", 2];
$myAssocArr = ["foo" => "bar"];
?>

<script>
var myInt = <?= json_encode($myInt) ?>;
var myString = <?= json_encode($myString) ?>;
var myArr = <?= json_encode($myArr) ?>;
var myAssocArr = <?= json_encode($myAssocArr) ?>;
</script>

This will render the following JS code, which correctly stores the variables:
<script>
var myInt = 7;
var myString = "\" ' ; &\\ $";
var myArr = [1,"str",2];
var myAssocArr = {"foo":"bar"};
</script>

Do note that there are no "s or anything like that around the json_encode output; json_encode handles that for you.
up
-20
starbugfourtytwo at gmail dot com
4 years ago
Why use such a complicated example for js to php? why not do this..so we can understand:

javascript:

const variable = "A"

php:

do whatever it takes to get A from javascript
up
-2
Anonymous
3 years ago
There is also a very easy XSS with the width and height parameters - they should be passed through htmlspecialchars
up
-2
Anonymous
3 years ago
I think the last example on this page may have a XSS vulnreability, e.g. sending the query string ?a="+alert('XSS')+" might cause alert('XSS') to be executed in the browser. The problem with that is that " will be percent encoded by the browser, but there could be some way to bypass the percent encoding and i think it's not good to rely on the percent encoding for security.
up
-62
Jay
10 years ago
If you have a really large form, be sure to check your max_input_vars setting.  Your array[] will get truncated if it exceeds this.  http://www.php.net/manual/en/info.configuration.php#ini.max-input-vars
up
-61
jetboy
18 years ago
While previous notes stating that square brackets in the name attribute are valid in HTML 4 are correct, according to this:

http://www.w3.org/TR/xhtml1/#C_8

the type of the name attribute has been changed in XHTML 1.0, meaning that square brackets in XHTML's name attribute are not valid.

Regardless, at the time of writing, the W3C's validator doesn't pick this up on a XHTML document.
To Top