php

51
Introdução Índice O que o PHP pode fazer? O que é PHP? PHP (um acrônimo recursivo para "PHP: Hypertext Preprocessor") é uma linguagem de script open source de uso geral, muito utilizada e especialmente guarnecida para o desenvolvimento de aplicações Web embútivel dentro do HTML. Ótimo, mas o que isso significa? Exemplo #1 Um exemplo introdutório <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Exemplo</title> </head> <body> <?php echo "Olá, Eu sou um script PHP!"; ?> </body> </html> Ao invés de muitos comandos para mostrar HTML (como visto em C ou Perl), páginas PHP contém HTML juntamente com códigos que fazem "alguma coisa" (neste caso, mostra "Olá, Eu sou um script PHP!") O código PHP é delimitado por tags iniciais e finais <?php e ?> que lhe permitem pular pra dentro e pra fora do "modo PHP". O que distingui o PHP de algo como Javascript no lado do cliente é que o código é executado no servidor, gerando HTML que é então enviado para o cliente. O cliente receberia os resultados da execução desse script, mas não saberia como é o código fonte. Você pode inclusive configurar seu servidor para processar todos os seus arquivos HTML como PHP, e então não haverá nenhum modo dos usuários descobrirem que se você usa essa linguagem ou não. A melhor coisa em usar PHP está no fato de ele ser extremamente simples para um iniciante, mas oferece muitos recursos para o programador profissional. Não se preocupe em ler as longas listas de funções do PHP. Você pode pular essa parte (por enquanto) e começar a escrever scripts em poucas horas.

Upload: anon-78398

Post on 13-Nov-2014

471 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Php

Introdução

Índice

O que o PHP pode fazer?

O que é PHP?

PHP (um acrônimo recursivo para "PHP: Hypertext Preprocessor") é uma linguagem de script open source de uso geral, muito utilizada e especialmente guarnecida para o desenvolvimento de aplicações Web embútivel dentro do HTML.

Ótimo, mas o que isso significa?

Exemplo #1 Um exemplo introdutório<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd"><html>    <head>        <title>Exemplo</title>    </head>    <body>

        <?php        echo "Olá, Eu sou um script PHP!";        ?>

    </body></html>

Ao invés de muitos comandos para mostrar HTML (como visto em C ou Perl), páginas PHP contém HTML juntamente com códigos que fazem "alguma coisa" (neste caso, mostra "Olá, Eu sou um script PHP!") O código PHP é delimitado por tags iniciais e finais <?php e ?> que lhe permitem pular pra dentro e pra fora do "modo PHP".

O que distingui o PHP de algo como Javascript no lado do cliente é que o código é executado no servidor, gerando HTML que é então enviado para o cliente. O cliente receberia os resultados da execução desse script, mas não saberia como é o código fonte. Você pode inclusive configurar seu servidor para processar todos os seus arquivos HTML como PHP, e então não haverá nenhum modo dos usuários descobrirem que se você usa essa linguagem ou não.

A melhor coisa em usar PHP está no fato de ele ser extremamente simples para um iniciante, mas oferece muitos recursos para o programador profissional. Não se preocupe em ler as longas listas de funções do PHP. Você pode pular essa parte (por enquanto) e começar a escrever scripts em poucas horas.

Apesar do desenvolvimento do PHP ser focado nos scripts do lado do servidor, você pode fazer muito mais com ele. Veja isso e leia mais na seção O que o PHP pode fazer?, ou diretamente no tutorial introdutório se você estiver interessado em programação web.

O que o PHP pode fazer? Começando

Page 2: Php

Last updated: Fri, 18 Jul 2008  

18-Aug-2007 07:48 before html runs to show a webpage, php code runs first on web server.

so, when there lines as follow:

<table><tr><td>  <?php    echo "php runs first!";  ?></td></tr></table>

the first step is to run php code, we get:

<table><tr><td>php runs first</td></tr></table>

then, code is sent to browser, and we see somthing~ george dot langley at shaw dot ca18-Jul-2007 05:02 "the code is executed on the server"

This is an important concept for the first-time PHP programmer to understand, so that when you get into string formatting later on, you understand the difference between formatting the on-screen content (as parsed by your browser) and formatting the HTML code (as returned by the server).For example "/n" starts a new line in the HTML code, and its results are only seen if you look at the "source HTML". It is NOT the same as <br>!

Um simples tutorial

Índice

Page 3: Php

Sua primeira página PHP Algo Útil

Tratando Formulários

Usando códigos antigos com a nova versão do PHP

O que mais?

Aqui nós iremos mostrar o básico do básico do PHP em um curto tutorial. Este texto fala somente sobre a criação de páginas dinâmicas com o PHP, visto que o PHP pode criar mais do que somente webpages. Veja a seção entitulada O que o PHP pode fazer para mais informações.

Fazer páginas com PHP é o mesmo que criar páginas HTML e você pode criá-las e editá-las da mesma maneira que faz com suas páginas HTML normal.

O que eu preciso?

Neste tutorial nós presumimos que seu servidor tem suporte ao PHP ativado e que todos os arquivos terminam com a extensão .php são tratados pelo PHP. Na maioria dos servidores esta é a extensão padrão para os arquivos PHP, mas pergunte ao seu administrador só para ter certeza. Se o seu servidor suporta PHP então você não precisa fazer mais nada. Apenas crie seus arquivos .php e coloque-os no seu diretório web e o servidor irá com um passe de mágica mostrar suas páginas PHP. Não há nenhuma necessidade de compilação para qualquer ferramenta extra. Pense nesses arquivos PHP como se eles fossem páginas HTML com algumas tags à mais que deixaram você fazer coisas mais interessantes do que somente páginas HTML estáticas.

Digamos que você quer salvar sua preciosa conexão e desenvolver tudo localmente. Neste caso, você precisará instalar um servidor web, como o » Apache, e claro o » PHP. Você também irá querer instalar uma base de dados, como por exemplo o » MySQL. Você pode instalá-los separadamente ou pelo jeito mais simples que é » usar os pacotes pré-configurados. que irão instalar automaticamente todas as coisas com apenas alguns cliques. É super fácil configurar um servidor web com suporte ao PHP em qualquer sistema operacional, incluindo Linux e Windows. No Linux, você deve procurar o » rpmfind que é muito útil na localização de pacotes RPM.

Sua primeira página PHP

Page 4: Php

Crie um novo arquivo chamado ola.php e coloque-o em seu diretório root do seu servidor web (DOCUMENT_ROOT) com o seguinte conteúdo:

Exemplo #1 Nosso primeiro script PHP: ola.php<html> <head>  <title>PHP Teste</title> </head> <body> <?php echo "<p>Olá Mundo</p>"; ?> </body></html>

Use o seu navegador para acessar o arquivo pelo endereço de seu servidor web, ao final do endereço coloque o arquivo "/ola.php" como referência. Quando o desenvolvimento é local você usará uma url como esta http://localhost/ola.php ou http://127.0.0.1/ola.php mas dependendo da configuração do seu servidor web. Entretanto isto está fora do escopo deste tutorial, veja também as diretivas DocumentRoot e ServerName dos arquivos de configuração do seu servidor web. (no Apache o nome do arquivo é httpd.conf). Se tudo foi configurado corretamente, o arquivo irá ser interpretado pelo PHP e irá mostrar a seguinte mensagem de saída no seu navegador:

<html> <head> <title>PHP Teste</title> </head> <body> <p>Olá Mundo</p> </body></html>

Note que isto não é como em um script CGI. O arquivo não precisa ser executável ou especial em nenhum aspecto. Pense nesse arquivo como um arquivo HTML normal mas com a diferença que ele pode conter algumas tags especiais à mais que permitem à você fazer coisas mais interessantes do que somente páginas HTML estáticas.

Este exemplo é extremamente simples e você realmente não precisa usar o PHP para criar uma página como esta. Tudo o que ele faz é mostrar uma mensagem Olá Mundo usando a declaração echo() do PHP.

Se você tentar rodar este exemplo e ele não mostrar nenhuma mensagem de saída, ou aparecer uma caixa de diálogo pedindo para você salvar o arquivo, ou você ver o arquivo em formato de texto, há uma grande chance do seu servidor não ter o PHP habilitado. Peça ao seu administrar para habilitar o PHP para você usando o capítulo de Instalação do manual. Se você está desenvolvendo localmente, também leia o capítulo indicado acima para ter certeza de que configurou tudo corretamente. Se os problemas continuarem à persistir, não hesite em usar uma das várias formas de » ajuda que o PHP pode lhe oferecer.

O objetivo do exemplo é mostrar o formato especial das tags do PHP. Neste exemplo nós usamos <?php para indicar que à partir daquele ponto começa um código PHP. Então nós colocamos uma declaração de fechamento para indicar que o script PHP acabou, usando a tag ?>. Você pode usar o PHP em qualquer parte do seu código HTML, e também pode usar várias tags de abertura e fechamento no

Page 5: Php

mesmo arquivo. Para mais detalhes, leia a seção do manual que fala da sintaxe básica do PHP.

Nota: Uma Nota sobre os Editores de Texto Há muitos editores de textos e Integrated Development Enviroments (IDEs) que você pode usar para criar, editar e gerenciar arquivos PHP. Uma lista parcial destas ferramentas pode ser vista na » Lista de Editores para PHP. Se você gostaria de recomendar algum editor, por favor visite o endereço acima e pergunte à gerenciador do site para adicionar o seu editor à lista. Ter um editor que colore as sintaxes das tags pode ser muito útil.

Nota: Uma Nota sobre os Processadores Word Processadores Word como o StarOffice Write, Microsoft Word e Abiword não são boas escolhas para editar arquivos PHP. Se você deseja usar um desses para testar seus scripts, você precisa verificar se você está salvando os arquivos como TEXTO PLANO ou o PHP não irá ser capaz de ler e executar o seu script.

Nota: Uma Nota sobre o Bloco de Notas do Windows Se você está escrevendo seus scripts PHP usando o Bloco de Notas do Windows, você precisará verificar que os arquivos estão sendo salvos com a extensão .php. (O Bloco de Notas do Windows adiciona automaticamente a extensão .txt aos arquivos à não ser que você siga um dos passos a seguir para previnir isto). Quando a caixa de diálogo Salvar estiver aberta e você for digitar o nome do seu arquivo, coloque o nome do arquivo entre aspas (i.e. "ola.php"). Uma alternativa, é você clicar na lista drop-down 'Documentos de Texto' na caixa de diálogo salvar e alterar para "Todos os tipos de arquivos". Você agora pode digitar o nome do seu arquivo sem usar as aspas.

Agora que você criou com sucesso um script simples em PHP, é hora de criar o mais famoso dos scripts PHP! Uma chamada à função phpinfo() e você verá todas as informações sobre seu sistema e configurações disponíveis como a de Variáveis Pré-definidas, módulos carregados pelo PHP, e as opções de configuração. Tire algum tempo para ver e rever estas importantes informações.

Algo Útil

Vamos fazer alguma coisa um pouco mais útil agora. Nós iremos checar qual é o tipo de navegador que o visitante está utilizando para ver a nossa página. De fato,

Page 6: Php

para fazer isto nós teremos que checar qual é o valor da string agente que o navegador envia como parte de sua requisição HTTP. Esta informação é armazenada em uma variável. Variáveis sempre começam com um símbolo de cifrão no PHP. A variável que nos interessa no momento é a $_SERVER["HTTP_USER_AGENT"].

Nota: Nota sobre as Auto-Globais do PHP $_SERVER é uma variável especial reservada do PHP que contém todas as informações sobre o servidor web. Ela é conhecida como uma Auto-Global (ou Superglobal). Veja a página do manual relacionada as Auto-globais para mais informações. Estas variáveis especiais foram introduzidas no PHP » 4.1.0. Antes desta versão, nós usávamos os velhos arrays $HTTP_*_VARS, como o $HTTP_SERVER_VARS. Entretanto, este estilo antingo foi removido, porém ainda existem. (Veja a nota sobre códigos antigos.)

Para chamar esta variável, nós podemos fazer isto:

Exemplo #1 Imprimindo a variável (Elemento Array)<?php echo $_SERVER["HTTP_USER_AGENT"]; ?>

Um exemplo de saída deste script poderia ser:

Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

Há muitos tipos de variáveis disponíveis no PHP. No exemplo acima nós escrevemos um elemento Array. Arrays podem ser muito úteis.

$_SERVER é somente uma variável que é automaticamente disponibilizada para você pelo PHP. Uma lista de Variáveis Reservadas pode ser vista na seção Variáveis Reservadas do manual ou você pode pegar uma lista completa delas criando um arquivo como este:

Exemplo #2 Exibindo todas as variáveis pré-definidas usando a função phpinfo()<?php phpinfo(); ?>

Se você carregar este arquivo no seu navegador você irá ver uma página com todas as informações sobre o PHP junto com uma lista de todos os tipos de variáveis disponíveis para você.

Você pode colocar mútiplas declarações PHP dentro da tag PHP e criar pequenos blocos de códigos que faem muito mais do que um simples echo. Por exemplo, se você quer checar se o navegador é o Internet Explorer faça algo como isso:

Exemplo #3 Exemplo usando controles de declarações e funções<?phpif (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {    echo "Você está usando o Internet Explorer<br />";}?>

Um exemplo de Saída seria:

Você está usando o Internet Explorer<br />

Aqui nós mostraremos alguns novos conceitos. Nós temos a declaração if. SE você é familiar com a sintaxe básica usada pela linguagem C isto parecerá ser lógico para

Page 7: Php

você. Se você não conhece a linguagem C ou alguma outra linguagem onde a sintaxe usada acima é usada, você provavelmente precisará de um livro introdutório sobre o PHP, dê uma lida nos primeiros capítulos do livro, ou leia a parte sobre a Referência da Linguagem no manual. Você pode encontrar uma lista de livros sobre PHP em at » http://www.php.net/books.php.

O segundo conceito que iremos abordar é a chamada à função strstr(). A função strstr() é trazida junto com o PHP, ela faz uma busca em uma palavra por uma outra palavra. Neste caso nós procuramos pela palavra "MSIE" dentro de $_SERVER["HTTP_USER_AGENT"]. Se a palavra for encontrada, a função returna TRUE e se ela não for encontrada a função retorna FALSE. Se o retorno for TRUE, a declaração if ocorre e o código dentro dela é executado. Caso contrário, o código não é executado. Sinta-se à vontade para criar exemplos similares com o if, else, e outras funções como a strtoupper() e strlen(). Cada uma delas está no manual com seus respectivos exemplos.

Nós podemos avançar agora e mostrar à você como alternar entre os modos PHP mesmo que você esteja executando blocos de códigos:

Exemplo #4 Mesclando entre os modos PHP e HTML<?phpif (strstr($_SERVER["HTTP_USER_AGENT"], "MSIE")) {?><h3>strstr retorna verdadeiro</h3><center><b>Você está usando o Internet Explorer</b></center><?php} else {?><h3>strstr retorna falso</h3><center><b>Você não está usando o Internet Explorer</b></center><?php}?>

Um exemplo de saída deste script poderia ser:

<h3>strstr retorna verdadeiro</h3><center><b>Você está usando o Internet Explorer</b></center>

Ao invés de usar a declaração echo do PHP para imprimir a saída dos dados, nós saímos do modo do PHP e usamos o HTML normal. O importante à notar aqui é que a lógica do script continua intacta. Somente alguns blocos HTML será enviados de acordo com o que a declaração strstr() retornar, ou seja TRUE ou FALSE. Em outras palavras, se a palavra MSIE for encontrada ou não.

Variáveis

Índice

Variáveis Pré-definidas

Page 8: Php

Escopo de variáveis

Variáveis variáveis

Variáveis de fontes externas

Introdução

As variáveis no PHP são representadas por um cifrão ($) seguido pelo nome da variável. Os nomes de variável no PHP fazem distinção entre maiúsculas e minúsculas.

Os nomes de variável seguem as mesmas regras como outros rótulos no PHP. Um nome de variável válido se inicia com uma letra ou sublinhado, seguido de qualquer número de letras, algarismos ou sublinhados. Em uma expressão regular isto poderia ser representado desta forma: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

Nota: Para nosso propósito, as letras a-z, A-Z e os caracteres ASCII de 127 a 255 (0x7f-0xff).

Nota: $this é uma variável especial que não pode ser atribuída.

Dica

Veja também o Guia de nomenclatura em espaço de usuário.

Para informação sobre funções relacionadas a variáveis, veja a Referência de funções para variáveis.

<?php$var = 'Bob';$Var = 'Joe';echo "$var, $Var";      // exibe "Bob, Joe"

$4site = 'not yet';     // inválido; começa com um número$_4site = 'not yet';    // válido; começa com um sublinhado$täyte = 'mansikka';    // válido; 'ä' é um caracter ASCII (extendido) 228?>

Por padrão, as variáveis são sempre atribuídas por valor. Isto significa que quando você atribui uma expressão a uma variável, o valor da expressão original é copiado integralmente para a variável de destino. Isto significa também que, após atribuir o valor de uma variável a outra, a alteração de uma destas variáveis não afetará a outra. Para maiores informações sobre este tipo de atribuição, veja o capítulo em Expressões.

O PHP oferece um outro meio de atribuir valores a variáveis: atribuição por referência. Isto significa que a nova variável simplesmente referencia (em outras palavras, "torna-se um apelido para" ou "aponta para") a variável original. Alterações na nova variável afetam a original e vice versa.

Para atribuir por referência, simplesmente adicione um e-comercial (&) na frente do nome da variável que estiver sendo atribuída (variável de origem) Por exemplo, o trecho de código abaixo imprime 'My name is Bob' duas vezes:

Page 9: Php

<?php$foo = 'Bob';              // Atribui o valor 'Bob' a variável $foo$bar = &$foo;              // Referecia $foo através de $bar.$bar = "My name is $bar";  // Altera $bar...echo $bar;echo $foo;                 // $foo é alterada também.?>

Uma observação importante a se fazer: somente variáveis nomeadas podem ser atribuídas por referência.

<?php$foo = 25;$bar = &$foo;      // Esta atribuição é válida.$bar = &(24 * 7);  // Inválido; referencia uma expressão sem nome.

function test(){   return 25;}

$bar = &test();    // Inválido.?>

Não é necessário variáveis inicializadas no PHP, contudo é uma ótima prática. Variáveis não inicializadas tem um valor padrão do tipo dela - FALSE, zero, string vazia ou um array vazio.

Exemplo #1 Valores padrões de variáveis não inicializadas<?phpecho ($unset_bool ? "true" : "false"); // false$unset_int += 25; // 0 + 25 => 25echo $unset_string . "abc"; // "" . "abc" => "abc"$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")?>

Confiar no valor padrão de uma variável não inicializada é problemático no caso de incluir um arquivo em outro que usa variável com mesmo nome. E também um principal risco de segurança com register_globals estando on. Erros E_NOTICE são emitidos no caso de ter variáveis não inicializadas, contudo não no caso de adicionar elementos para um array não inicializado. O construtor da linguagem isset() pode ser usado para detectar se uma variável não foi inicializada.

Variáveis Pré-definidas Manipulação de tipos

Last updated: Fri, 18 Jul 2008  

User Contributed Notes

Variáveis Anonymous20-Jul-2008 06:25 [EDIT by danbrown AT php DOT net: The function provided by this author will give you all defined variables at runtime.  It was originally written by (john DOT t DOT gold AT gmail DOT com), but contained some

Page 10: Php

errors that were corrected in subsequent posts by (ned AT wgtech DOT com) and (taliesin AT gmail DOT com).]

<?php

echo '<table border=1><tr> <th>variable</th> <th>value</th> </tr>'; foreach( get_defined_vars() as $key => $value) {     if (is_array ($value) )     {         echo '<tr><td>$'.$key .'</td><td>';         if ( sizeof($value)>0 )         {         echo '"<table border=1><tr> <th>key</th> <th>value</th> </tr>';         foreach ($value as $skey => $svalue)         {             echo '<tr><td>[' . $skey .']</td><td>"'. $svalue .'"</td></tr>';         }         echo '</table>"';         }              else         {             echo 'EMPTY';         }         echo '</td></tr>';     }     else     {             echo '<tr><td>$' . $key .'</td><td>"'. $value .'"</td></tr>';     } } echo '</table>'; ?> alexandre at nospam dot gaigalas dot net06-Jul-2007 09:13 Here's a simple solution for retrieving the variable name, based on the lucas (http://www.php.net/manual/en/language.variables.php#49997) solution, but shorter, just two lines =)

<?phpfunction var_name(&$var, $scope=0){    $old = $var;    if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;  }?> jsb17 at cornell dot edu20-Feb-2007 08:48 As an addendum to David's 10-Nov-2005 posting, remember that curly braces literally mean "evaluate what's inside the curly braces" so, you can squeeze the variable variable creation into one line, like this:

<?php  ${"title_default_" . $title} = "selected";?>

Page 11: Php

and then, for example:

<?php  $title_select = <<<END    <select name="title">      <option>Select</option>      <option $title_default_Mr  value="Mr">Mr</option>      <option $title_default_Ms  value="Ms">Ms</option>      <option $title_default_Mrs value="Mrs">Mrs</option>      <option $title_default_Dr  value="Dr">Dr</option>    </select>END;?> code at slater dot fr25-Jan-2007 02:10 Here's a pair of functions to encode/decode any string to be a valid php and javascript variable name.

<?php

function label_encode($txt) {    // add Z to the begining to avoid that the resulting   // label is a javascript keyword or it starts with a   // number  $txt = 'Z'.$txt;    // encode as urlencoded data  $txt = rawurlencode($txt);    // replace illegal characters  $illegal = array('%', '-', '.');  $ok = array('é', 'è', 'à');  $txt = str_replace($illegal,$ok, $txt);    return $txt;}

function label_decode($txt) {    // replace illegal characters  $illegal = array('%', '-', '.');  $ok = array('é', 'è', 'à');  $txt = str_replace($ok, $illegal, $txt);    // unencode  $txt = rawurldecode($txt);    // remove the leading Z and return  return substr($txt,1);}

?> molnaromatic at gmail dot com20-May-2006 05:44 Simple sample and variables and html "templates":The PHP code:variables.php:<?php$SYSN["title"] = "This is Magic!";$SYSN["HEADLINE"] = "Ez magyarul van"; // This is hungarian

Page 12: Php

$SYSN["FEAR"] = "Bell in my heart";?>

index.php:<?phpinclude("variables.php");include("template.html");?>

The template:template.html

<html><head><title><?=$SYSN["title"]?></title></head><body><H1><?=$SYSN["HEADLINE"]?></H1><p><?=$SYSN["FEAR"]?></p></body></html>This is simple, quick and very flexibile Mike at ImmortalSoFar dot com25-Nov-2005 02:03 References and "return" can be flakey:

<?php//  This only returns a copy, despite the dereferencing in the function definitionfunction &GetLogin (){    return $_SESSION['Login'];}

//  This gives a syntax errorfunction &GetLogin (){    return &$_SESSION['Login'];}

//  This worksfunction &GetLogin (){    $ret = &$_SESSION['Login'];    return $ret;}?> david at removethisbit dot futuresbright dot com10-Nov-2005 01:25 When using variable variables this is invalid:

<?php $my_variable_{$type}_name = true; ?>

to get around this do something like:

<?php $n="my_variable_{$type}_name"; ${$n} = true; ?>

Page 13: Php

(or $$n - I tend to use curly brackets out of habit as it helps t reduce bugs ...) Chris Hester31-Aug-2005 05:09 Variables can also be assigned together.

<?php$a = $b = $c = 1;echo $a.$b.$c;?>

This outputs 111. Mike Fotes09-Jul-2005 11:46 In conditional assignment of variables, be careful because the strings may take over the value of the variable if you do something like this:

<?php$condition = true;

// Outputs " <-- That should say test"echo "test" . ($condition) ? " <-- That should say test" : "";?>

You will need to enclose the conditional statement and assignments in parenthesis to have it work correctly:

<?php$condition = true;

// Outputs "test <-- That should say test"echo "test" . (($condition) ? " <-- That should say test " : "");?> josh at PraxisStudios dot com17-May-2005 01:06 As with echo, you can define a variable like this:

<?php

$text = <<<END

<table>     <tr>         <td>              $outputdata         </td>      </tr> </table>

END;

?>

The closing END; must be on a line by itself (no whitespace).

[EDIT by danbrown AT php DOT net: This note illustrates HEREDOC syntax.  For more information on this and similar features, please read the "Strings" section of the manual here: http://www.php.net/manual/en/language.types.string.php ] mike at go dot online dot pt07-Apr-2005 09:18

Page 14: Php

In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:

<?php//considering 2 arrays$foo1 = array ("a", "b", "c");$foo2 = array ("d", "e", "f");

//and 2 variables that hold integers$num = 1;$cell = 2;

echo ${foo.$num}[$cell]; // outputs "c"

$num = 2;$cell = 0;

echo ${foo.$num}[$cell]; // outputs "d"?> lucas dot karisny at linuxmail dot org14-Feb-2005 04:42 Here's a function to get the name of a given variable.  Explanation and examples below.

<?php  function vname(&$var, $scope=false, $prefix='unique', $suffix='value')  {    if($scope) $vals = $scope;    else      $vals = $GLOBALS;    $old = $var;    $var = $new = $prefix.rand().$suffix;    $vname = FALSE;    foreach($vals as $key => $val) {      if($val === $new) $vname = $key;    }    $var = $old;    return $vname;  }?>

Explanation:

The problem with figuring out what value is what key in that variables scope is that several variables might have the same value.  To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match.  Then we loop through the scope the variable is contained in and when there is a match of our modified value, we can grab the correct key.

Examples:

1.  Use of a variable contained in the global scope (default):<?php  $my_global_variable = "My global string.";  echo vname($my_global_variable); // Outputs:  my_global_variable?>

2.  Use of a local variable:<?php  function my_local_func()

Page 15: Php

  {    $my_local_variable = "My local string.";    return vname($my_local_variable, get_defined_vars());  }  echo my_local_func(); // Outputs: my_local_variable?>

3.  Use of an object property:<?php  class myclass  {    public function __constructor()    {      $this->my_object_property = "My object property  string.";    }  }  $obj = new myclass;  echo vname($obj->my_object_property, $obj); // Outputs: my_object_property?> jospape at hotmail dot com04-Feb-2005 11:45 <?php $id = 2; $cube_2 = "Test";

echo ${cube_.$id};

// will output: Test ?> ringo78 at xs4all dot nl14-Jan-2005 12:27 <?php // I am beginning to like curly braces. // I hope this helps for you work with them $filename0="k"; $filename1="kl"; $filename2="klm";  $i=0; for ($varname = sprintf("filename%d",$i);   isset  ( ${$varname} ) ;   $varname = sprintf("filename%d", $i)  )  {     echo "${$varname} <br>";     $varname = sprintf("filename%d",$i);     $i++; } ?> Carel Solomon07-Jan-2005 03:02 You can also construct a variable name by concatenating two different variables, such as:

<?php

$arg = "foo"; $val = "bar";

//${$arg$val} = "in valid";     // Invalid ${$arg . $val} = "working";

echo $foobar;     // "working"; //echo $arg$val;         // Invalid

Page 16: Php

//echo ${$arg$val};     // Invalid echo ${$arg . $val};    // "working"

?>

Carel raja shahed at christine nothdurfter dot com25-May-2004 10:58 <?phperror_reporting(E_ALL);

$name = "Christine_Nothdurfter";// not Christine Nothdurfter// you are not allowed to leave a space inside a variable name ;)$$name = "'s students of Tyrolean language ";

print " $name{$$name}<br>";print  "$name$Christine_Nothdurfter";// same?> webmaster at daersys dot net20-Jan-2004 08:15 You don't necessarily have to escape the dollar-sign before a variable if you want to output its name.

You can use single quotes instead of double quotes, too.

For instance:

<?php $var = "test";

echo "$var"; // Will output the string "test"

echo "\$var"; // Will output the string "$var"

echo '$var'; // Will do the exact same thing as the previous line ?>

Why? Well, the reason for this is that the PHP Parser will not attempt to parse strings encapsulated in single quotes (as opposed to strings within double quotes) and therefore outputs exactly what it's being fed with :)

To output the value of a variable within a single-quote-encapsulated string you'll have to use something along the lines of the following code:

<?php $var = 'test'; /* Using single quotes here seeing as I don't need the parser to actually parse the content of this variable but merely treat it as an ordinary string */

echo '$var = "' . $var . '"'; /* Will output: $var = "test"

Page 17: Php

*/ ?>

HTH - Daerion unleaded at nospam dot unleadedonline dot net14-Jan-2003 06:37 References are great if you want to point to a variable which you don't quite know the value yet ;)

eg:

<?php $error_msg = &$messages['login_error']; // Create a reference

$messages['login_error'] = 'test'; // Then later on set the referenced value

echo $error_msg; // echo the 'referenced value' ?>

The output will be:

test

Tratando Formulários

Uma das características mais fortes do PHP é o jeito como ele trata formulários HTML. O conceito básico que é importante entender é que qualquer elemento de formulário em um formulário irá automaticamente ficar disponível para você usá-los em seus scripts PHP. Por favor leia a seção Variáveis externas do PHP para mais informaçõess exemplos de como usar formulários com PHP. Aqui vai um exemplo:

Exemplo #1 Um simples formulário HTML<form action="acao.php" method="POST"> Seu nome <input type="text" name="nome" /> Sua idade: <input type="text" name="idade" /> <input type="submit"></form>

Não há nada de especial neste formulário. É um formulário HTML comum sem nenhuma tag especial de qualquer tipo. Quando o usuário preencer este formulário e clicar no botão enviar, a página action.php é chamada. Neste arquivo nós teremos algo como este:

Exemplo #2 Imprimindo dados de nosso formulárioOi <?php echo $_POST["nome"]; ?>.Você tem <?php echo $_POST["idade"]; ?> anos.

Um exemplo de saída deste script seria:

Oi Thomas.Você tem 18 anos.

Page 18: Php

É óbvio o que este script faz. Não há nada de mais nele. As variáveis $_POST["nome"] e $_POST["idade"] são automaticamente criadas para você pelo PHP. Antigamente nós usávamos a auto-global $_SERVER, agora nós simplesmente usamos a auto-global $_POST que contém todos os dados vindos do POST. Se você usar o método GET então nossas informações residirão na auto-global $_GET. Você também pode usar a auto-global $_REQUEST se você não se importa com o tipo de dados que vêm do seu formulário. Esta auto-global contém uma mescla de GET, POST, COOKIE e FILE. Veja também a função import_request_variables().

Usando códigos antigos com a nova versão do PHP Algo Útil

Last updated: Fri, 18 Jul 2008  

User Contributed Notes

Tratando Formulários arnel_milan at hotmail dot com29-Mar-2008 10:27 I was so shocked that some servers have a problem regarding the Submit Type Name and gives a "Not Acceptable error" or Error 406.

Consider the example below :

<form action="blah.php" method="POST">  <table>    <tr>      <td>Name:</td>      <td><input type="text" name="name"></td>    </tr>        <tr>      <td colspan="2" align="center">        <input type="submit" name="Submit_btn" id="Submit_btn" value="Send">      </td>    </tr>    </table></form>

This very simple code triggers the "Not Acceptable Error" onPHP Version 5.2.5 and Apache 1.3.41 (Unix) Server.

However to fix this below is the right code:

<form action="blah.php" method="POST">  <table>    <tr>      <td>Name:</td>      <td><input type="text" name="name"></td>    </tr>        <tr>      <td colspan="2" align="center">        <input type="submit" name="Submitbtn" id="Submit_btn" value="Send">      </td>    </tr>    </table>

Page 19: Php

</form>

The only problem that took me hours to find out is the "_" in the Submit Button.

Hope this help! Lord Pacal03-Jan-2008 06:38 One thing that tripped me up when I was first learning PHP was the use of the NAME attribute in form fields. The current convention is to use the ID attribute instead when creating forms. (Many HTML editors automatically include an ID attribute without a NAME attribute.) Now, I include both the NAME and ID attributes (with the same value) in all my form fields.

For example...<form method="post"><input type="text" id="field1"><input type="submit" value="go"></form>

If you then have a PHP page requesting the contents of the "field1" field...<?php echo $_POST["field1"] ?>...the above form will always return an empty string for "field1".

The solution is to include the NAME attribute...<form method="post"><input type="text" id="field1" name="field1"><input type="submit" value="go"></form>

With this change, the PHP code will correctly retrieve the value of the "field1" field. SvendK08-Nov-2006 08:02 As Seth mentions, when a user clicks reload or goes back with the browser button, data sent to the server, may be sent again (after a click on the ok button).

It might be wise, to let the server handle whatever there is to handle, and then redirect (a redirect is not visible in the history and thus not reachable via reload or "back".

It cannot be used in this exact example, but as Seth also mentions, this example should be using GET instead of POST yasman at phplatvia dot lv05-May-2005 12:18 [Editor's Note: Since "." is not legal variable name PHP will translate the dot to underscore, i.e. "name.x" will become "name_x"]

Be careful, when using and processing forms which contains <input type="image"> tag. Do not use in your scripts this elements attributes `name` and `value`, because MSIE and Opera do not send them to server. Both are sending `name.x` and `name.y` coordiante variables to a server, so better use them. sethg at ropine dot com

Page 21: Php

Last updated: Fri, 18 Jul 2008 view this page in Sintaxe BásicaÍndiceSeparação de instruções

Comentários

Escapando o HTML

Quando o PHP interpreta um arquivo, ele procura pelas tags de abertura e fechamento, as quais indicam para o PHP começar e parar de interpretar o código entre elas. interpretar desta maneira permite ao PHP ser embutido em todos os tipos de documentos diferentes, já que tudo fora o par de tags de abertura e fechamento é ignorado pelo interpretador do PHP. A maioria das vezes você verá o PHP embutido em documentos HTML como neste exemplo.

<p>Isto vai ser ignorado.</p><?php echo 'Enquanto isto vai ser interpretado.'; ?><p>Isto também vai ser ignorado.</p>

Você também pode usar estruturas mais avançadas:

Exemplo #1 Escapando de modo avançado<?phpif ($expression) {    ?>    <strong>Isto é verdadeiro.</strong>    <?php} else {    ?>    <strong>Isto é falso.</strong>    <?php}?>

Isto funciona como o esperado, porque o quando PHP atinge o ?> fechando as tags, ele simplesmente começa a enviar para a saída qualquer coisa (exceto newlines em seguida - veja separação de instruções) que encontre até que atinja outra tag de abertura. O exemplo dado aqui é resumido, claro, mas para escrever grandes blocos de texto, sair do modo de interpretação do PHP é geralmente mais eficiente do que enviar todo o texto atráves de echo() ou print().

Existem quatro diferentes pares de tags de abertura e fechamento que podem ser usados com o PHP. Duas dessas, <?php ?> e <script language="php"> </script>, estão sempre disponíveis. As outras duas são tags curtas e tags no estilo ASP, e podem ser ativadas e desativadas a partir do arquivo de configuração php.ini. Assim, enquanto algumas pessoas acham as tags curtas e tags no estilo ASP conveniente, elas são menos portáveis, e geralmente não recomendadas.

Nota: Também note que se você esta embutindo o PHP no XML ou XHTML você irá precisar usar as tags <?php ?> para permanecer cumprindo com os padrões.

Exemplo #2 Abrindo e Fechando as Tags do PHP1.  <?php echo 'se você quer servir documentos XHTML ou XML, faça assim'; ?>

2.  <script language="php">        echo 'alguns editores (como FrontPage) não              gostam de instruções de processamento';

Page 22: Php

    </script>

3.  <? echo 'esta é a mais simples, uam instrução de processamento SGML'; ?>    <?= expressão ?> Isto é um atalho para "<? echo expressão ?>"

4.  <% echo 'Você pode opcionalmente usar tags no estilo ASP'; %>    <%= $variavel; # Isto é um atalho para "<% echo . . ." %>

Enquanto as tags vistas nos exemplos um e dois estão ambas sempre disponíveis, o exemplo um é mais comumente usado, e recomendado, das duas.

Tags curtas (exemplo três) estão disponíveis apenas quando são ativadas pela configuração short_open_tag no arquivo php.ini ou se o PHP foi configurado com a opção --enable-short-tags.

Tags no estilo ASP (exemplo quatro estão disponíveis apenas quando elas estão ativadas atráves da diretiva de configuração asp_tags no arquivo php.ini.

Nota: O uso de tags curtas deve ser evitado ao desenvolver aplicações ou bibliotecas que serão redistribuidas, ou serão usadas em servidores PHP que não estão sobre o seu controle, porque as tags curtas podem não ser suportadas no servidor em questão. Para código portável, redistribuível, tenha certeza de não usar tags curtas.

Separação de instruções Referência da Linguagem

Last updated: Fri, 18 Jul 2008  

User Contributed Notes

Sintaxe Básica mattsch at gmail dot com25-Jun-2008 01:46 Less is more.  The shortest and easiest way to deal with the xml tag problem assuming short tags is enabled and you don't care to listen to people who want you to always use the full php tag is this:

<<??>?xml version="1.0" encoding="utf-8"?> jesdisciple{ at t}gmail{d dot t}com05-Mar-2008 09:21 @evanplaice at aol dot com: The <script language="php"> tag won't be read by browsers; it will be parsed by PHP just like <?php and ?> are. evanplaice at aol dot com30-Dec-2007 03:33 Correction for Example 2-2

The <script> "language" attribute has been deprecated

See: http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.2.1

This should be noted in the example to update to the current standards. KOmaSHOOTER at gmx dot de28-Dec-2007 07:36

Page 23: Php

you also can use this kind of syntax:

<?php if( condition ): ?>  <?php else: ?>  <?php endif; ?> truepath at infiniteinjury dot org15-Jul-2007 01:08 "This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds"

This is worded very confusingly so if you think you know what's going on just ignore this (I knew how this had to work from ruby but this comment made me think I was confused).  To be clear the documentation is NOT saying that whenever the PHP *parser* hits the closing tag it starts outputting whatever if finds.  What they mean is that ?> acts just like a php instruction that outputs whatever text it finds until it sees a <?php Tona at spikesource dot com03-May-2007 03:22 Jascam: Try to find more resourceful information to make your point. Your lack of ability to understand more complex concepts is not enough to diminish such a popular language as PHP. Note also that php is not replacing html but complementing it. madman17-Apr-2007 08:45 As rosswilliams mentioned;  The example breaking in and out of the PHP tags doesn't "work as expected".  The manual and some comments mention that PHP "simply starts outputting whatever it finds..." any time a closing tag is encountered.  It would make sense to say instead - "...unless PHP is in the middle of a conditional statement; in which case it will only output the relevant block of HTML."

Some have said that using the 'echo' command is cleaner and more  efficient.  However, as the manual points out, the method of breaking out of PHP is more efficient when dealing with large sections of HTML.  Because there is less work for the parser. Geekman at Textbook Torrents dot com04-Mar-2007 05:19 Regarding the comment by rosswilliams at advocacytechnologies dot org:

Your suspicion is correct. The following all behave exactly the same:

<?php

// output the answer by escapingif ($true_or_false) {    ?>    <p>The value of $true_or_false is true.</p>    <?php} else {    ?>    <p>The value of $true_or_false is false.</p>    <?php}

// use echo to do the same thing - more effecient and easier to read in my opinionif ($true_or_false) {    echo '<p>The value of $true_or_false is true.</p>';

Page 24: Php

} else {    echo '<p>The value of $true_or_false is false.</p>';}

// use ? : operators on entire stringecho ($true_or_false) ? '<p>The value of $true_or_false is true.</p>' : '<p>The value of $true_or_false is false.</p>';

// use ? : operators only on the pertinent bit, to save spaceecho '<p>The value of $true_or_false is ' . (($true_or_false) ? 'true' : 'false') . '.</p>';

?> rosswilliams at advocacytechnologies dot org29-Dec-2006 11:14 "This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting whatever it finds until it hits another opening tag."

I would suggest it is not clear what "works as expected" means. You may know what to expect. But as a new user I don't.

The explanation would lead one to believe both phrases outside the php code would be outputted to the html document. I suspect that is not what happens, but I will need to go test it. alfridus23-Jul-2006 04:53 Only this work:

<?php $xml = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>';echo $xml; ?>

with space after '<?php' and before ' ?>', no spacing between'<?xml' and a semicolon after '"no"?>';'. php at pixo dot sk04-Apr-2006 04:58 just for conclusion:

<?php echo('<?xml version="1.0" ?'.'>'); ?>

is the right choice :) brettz9 at yahoo dot com02-Apr-2006 08:04 I've essentially tried to synthesize thisdiscussion at http://en.wikibooks.org/wiki/Programming:Complete_PHP/Escaping_from_HTML

One point not brought up yet...

The HEREDOC problem with some text editorsmay be fixable in at least some text editorsby adding a comment with a quotation markas such afterwards (albeit necessarily on anew line):

<?php

$version = "1.0";

Page 25: Php

print <<<HERE<?xml version="HERE;//"

print $version."\"?>";

?> Christoph16-Jan-2006 05:08 Here's an inspiration on how to quickly fix all scripts relying on short_open_tag being enabled:

find -name '*.php' | xargs perl -pi -e 's/<\?= ?(.*?) ?\?>/<?php echo($1); ?>/g'find -name '*.php' | xargs perl -pi -e 's/<\?/<?php/g'find -name '*.php' | xargs perl -pi -e 's/<\?phpphp/<?php/g' Michael Newton (http://mike.eire.ca/)12-Dec-2005 03:17 The XML declaration does not need to be handled specially.

You should output it via an echo statement, in case your code is ever used on a server that is (poorly) configured to use short open tags.

But there's no need to treat the ?> at the end of the string specially.  That's because it's in a string.  The only thing PHP ever looks for in a string is \ or $ (the latter only in double-quoted strings.)

I have never had need for the following, as some have suggested below:

<?php$xml=rawurldecode('%3C%3Fxml%20version%3D%221.0%22%3F%3E');echo($xml);?>

<?php echo '<?xml version="1.0" ?'.'>' ?>

<?php echo "<?xml version=\"1.0\"\x3F>" ?> php [AT] jsomers [DOT] be23-Sep-2005 12:37 PEAR states:

Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups.

It are these small things that enhance readability in group projects, or libraries. pablo [] littleQ.net24-Jul-2005 02:06 Just another more "feature" of IE...

Content-Disposition: attachment; filename=\"__FILE__\";

__FILE__ can't have spaces or :

Regards 01karlo at gmail dot com25-Jun-2005 08:44

Page 26: Php

Or, use the following:

<?php$xml=rawurldecode('%3C%3Fxml%20version%3D%221.0%22%3F%3E');echo($xml);?>

What is does it the value of the variable $xml is the RAW Url Encoded version of the XML thing.Then it decodes it and echo it to the visitor. p o r g e s at the gmail dot com server01-Apr-2005 08:02 mike at skew dot org, I believe the differentiation is that "x"-"m"-"l" as a PI target is explicitly excluded from the definition of processing instructions. Lachlan Hunt28-Mar-2005 09:06 The person that suggested the use of this meta element above is wrong:

<meta http-equiv="Content-Type" content="application/xml+xhtml; charset=UTF-8" />

That meta element and the XML declaration serve completely different purposes, and that meta element should not be used.  Such information should be set using the HTTP Content-Type header (see the header() function).

Any XHTML page that just uses that meta element without proper HTTP Content-Type header, will be processed as text/html by browsers regardless, and when the HTTP headers do serve as application/xhtml+xml (or other XML MIME type), that charset parameter in the meta element will be ignored. mike at skew dot org21-Oct-2004 04:53 mart3862 mentions "XML processing instructions" and quotes their syntax from the spec, but is mistaken in using

<?xml version="1.0" ...?>

as an example. This little bit of markup that appears at the beginning of an XML file is in fact not a processing instruction at all; it is an "XML declaration" -- or, if it appears in an entity other than the main document, a "text declaration". All three constructs are formatted slightly differently, although they all do begin and end with the same.

The difference between a processing instruction, an XML declaration, or a text declaration is more than just a matter of subtle differences in syntax, though. A processing instruction embodies exactly two opaque, author-defined pieces of information (a 'target' and an 'instruction') that are considered to be part of the document's logical structure and that are thus made available to an application by the XML parser. An XML or text declaration, on the other hand, contains one to three specific pieces of information (version, encoding, standalone status), each with a well-defined meaning. This info provides cues to the parser to help it know how to read the file; it is not considered part of the document's logical structure and is not made available to the application. stooges_cubed at racerx dot net20-Oct-2004 01:13

Page 27: Php

In the note above about escaping XML/PHP style <?xml tags, the following code was used:

<?php  // Html safe containers

   echo <<<EOD <?xml version="1.0"?> ...all sorts of XML goes here... Nothing will affect the output of this code until: EOD; ?>

EOD is just an example stop/start name.

This works too:

<?php  // Html safe containers

  $myOutput = <<<MYHTMLSAFEOUTPUT <?xml version="1.0"?> <html>   <title>PHP Example</title>   <body>    <p>...all sorts goes here...</p>   </body> </html> MYHTMLSAFEOUTPUT;

echo $myOutput;

?>

Only disadvantage of using this is that all the code highlighting programs I've seen never get it right, making your code look eronous in the majority of viewers.

Another alternative is to keep the XML / HTML in a separate include file and read in when needed. I don't know how efficient/inefficient this is for (idiots like yourselves) small amounts of text.

xmlheader.txt: <?xml version="1.0"?>

mypage.php: <?php   include("xmlheader.txt"); ?> crtrue at coastal dot edu30-Apr-2004 11:02 Although you can use the above methods to pass a document off as a valid for the W3C parser, a simpler-and-perfectly-legal method of doing so is to simple declare the document type in a meta tag. Something along these lines (mind the values in 'content' - I haven't personally used the Content-Type method in awhile):

<meta http-equiv="Content-Type" content="application/xml+xhtml; charset=UTF-8" />

Of course if you're using just XML, and don't use such functions, then the above methods will work just as fine.

Page 28: Php

mart3862 at yahoo dot com dot au18-Apr-2004 09:29 Now the ultimate truth on how you should output xml processing instructions:

There have been several posts suggesting ways to include the text <?xml version="1.0" encoding="utf-8"?> in your output when short_tags is turned on, but only the following should be used:

<?php echo '<?xml version="1.0" ?'.'>' ?>or<?php echo "<?xml version=\"1.0\"\x3F>" ?>

Using one of these methods, and not making use of short tags, means your source code will also be a valid XML document, which allows you to do many things with it such as validation, XSLT translations, etc, as well as allowing your text editor to parse your code for syntax colouring.  Every PHP tag will simply be interpreted as an XML processing instruction (commonly referred to as PI).

The reason why all the other suggested methods are not advisable is because they contain the characters ?> inside the PHP tag, which the XML parser will interpret as the end of the processing instruction.

A processing instruction is defined in XML as:

PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'

In other words, it explicitly forbids the characters ?> to occur together within a processing instruction, unless they are delimiting the end of the tag.  It also requires a PITarget (an identifier starting with a letter) immediately after the initial start delimiter, which means that all short tag formats are also invalid XML.

Following these guidelines will result in code that is portable to servers with any configuration and allow you perform many useful tasks on your XML or XHTML source documents.  Even if you do not intend to validate or translate your source documents, and you can ignore some incorrect syntax colouring in your text editor, it is still best to get into good habits early. Anon21-Feb-2004 06:05 Yet another way of adding the XML processing instruction is to use:

<?php echo '<?xml version="1.0" ?'.'>' ?>

Because the ? and > are separated, the parser will not terminate before it is supposed to.

As a side note, the W3C's parser seems to recognise this method (assuming it even checks for the PI). TarquinWJ06-Feb-2004 06:54 Not spotted any messages like this one - delete it if there was one.

My hosting service allows <? and ?>, but I like to use valid XHTML, so I came up with this simple solution:

It is possible to use the short tags <? ?> with XHTML or XML documents. The only problem is that X(HT)ML requires a declaration using <? and ?>

Page 29: Php

<?xml version="1.0" encoding="UTF-8"?>

To avoid the problem, simply replace <? with <<? ?>?and ?> with ?<? ?>>

<<? ?>?xml version="1.0" encoding="UTF-8"?<? ?>>

This inserts a blank piece of PHP in between the < and ?, and when parsed will output the regular tag<?xml version="1.0" encoding="UTF-8"?> mwild at iee dot NO_SP_AM dot org19-Dec-2003 05:12 The text between <script> and </script> in XHTML is PCDATA, so <  and & characters in it should be interpreted as markup. This is a bit limiting for PHP, which is often used to output tags, though you can of course use &lt; and &amp; instead. To avoid that, which makes your code look peculiar and is easy to forget to do, you can mark the PHP as CDATA, eg :

<script language="PHP">//<![CDATA[ echo('Today is <b>'.date('l F jS').'</b>');//]]></script>

If you don't do this, and your code contains < or &, it should be rejected by an XHTML validator. johnbeech at (not saying) mkv25 dot net07-Dec-2003 04:42 In the note above about escaping XML/PHP style <?xml tags, the following code was used:

<?php  // Html safe containers

   echo <<<EOD<?xml version="1.0"?>...all sorts of XML goes here...Nothing will affect the output of this code until:   EOD;?>

EOD is just an example stop/start name.

This works too:

<?php  // Html safe containers

  $myOutput = <<<MYHTMLSAFEOUTPUT<?xml version="1.0"?><html>  <title>PHP Example</title>  <body>    <p>...all sorts goes here...</p>  </body></html>MYHTMLSAFEOUTPUT;

echo $myOutput;

?>

Page 30: Php

Only disadvantage of using this is that all the code highlighting programs I've seen never get it right, making your code look eronous in the majority of viewers.

Another alternative is to keep the XML / HTML in a separate include file and read in when needed. I don't know how efficient/inefficient this is for small amounts of text.

xmlheader.txt:<?xml version="1.0"?>

mypage.php:<?php  include("xmlheader.txt");?> dave at [nospam] dot netready dot biz18-Mar-2002 04:21 A little "feature" of PHP I've discovered is that the <?PHP token requires a space after it whereas after the <? and <% tokens a space is optional.

The error message you get if you miss the space is not too helpful so be warned!

(These examples only give a warning with error_reporting(E_ALL) )

<?PHP/*<Some HTML>*/?> fails...<?/*<Some HTML>*/?> works... mrtidy at mail dot com12-Dec-2001 12:36 [Ed Note: This is because of short_tags, <?xml turns php parsing on, because of the <?. [email protected]]

I am moving my site to XHTML and I ran into trouble with the <?xml ?> interfering with the <?php ?> method of escaping for HTML.  A quick check of the mailing list confirmed that the current preferred method to cleanly output the <?xml ?> line is to echo it:<br> <?php echo("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); ?>

Separação de instruções

Como no C ou Perl, o PHP requer que as instruções sejam terminadas com um ponto-e-vírgula ao final de cada comando. A tag de fechamento de um bloco de código PHP automaticamente implica em um ponto-e-vírgula; você não precisa ter um ponto-e-vírgula terminando a última linha de um bloco PHP. A tag de fechamento irá incluir uma nova linha logo após, se estiver presente.

<?php    echo 'Este é um teste';?>

<?php echo 'Este é um teste' ?>

<?php echo 'Nós omitimos a última tag de fechamento';

Page 31: Php

Nota: A tag de fechamento de um bloco PHP ao final de um arquivo é opcional, e em alguns casos omiti-la é útil ao usar include() ou require(), assim espaço em branco indesejado não irá aparecer ao final dos arquivos, e você ainda será capaz de adicionar cabeçalhos a resposta após. Também é útil se você usar output buffering, e você não quer ter adicionado espaço em branco ao final de partes geradas por arquivos incluídos.

Expressões

Expressões são as peças de construção mais importantes do PHP. No PHP, quase tudo o que você escreve são expressões. A maneira mais simples e ainda mais precisa de definir uma expressão é "tudo o que tem um valor".

As formas mais básicas de expressões são constantes e variáveis. Quando você digita "$a = 5", você está atribuindo '5' para $a. '5', obviamente, tem o valor 5, ou, em outras palavras, '5' é uma expressão com o valor 5 (neste caso, '5' é uma constante inteira).

Depois desta atribuição, você pode esperar que o valor de $a seja 5 também, assim se você escrever $b = $a, você pode esperar que $b se comporte da mesma forma que se você escrevesse $b = 5. Em outras palavras, $a é uma expressão com valor 5 também. Se tudo funcionou bem, isto é exatamente o que acontecerá.

Page 32: Php

Exemplos ligeiramente mais complexos para expressões são as funções. Por exemplo, considere a seguinte função:

<?phpfunction foo (){    return 5;}?>

Assumindo que você está familiarizado com o conceito de funções (se não estiver, dê uma olhada no capítulo sobre functions), você pode assumir que digitar $c = foo() é essencialmente a mesma coisa que escrever $c = 5, e você está certo. Funções são expressões com o valor igual ao seu valor de retorno. Como foo() retorna 5, o valor da expressão 'foo()' é 5. Geralmente, as funções não retornam apenas um valor estático, mas computam algo.

Claro, valores em PHP não tem que ser inteiros, e muito comumente eles não são. o PHP suporta quatro tipos de valores escalares: valores integer (inteiros), valores de ponto flutuante (float), valores string (caracteres) e valores boolean (booleano) (valores escalares são valores que você não pode partir em peças menores, diferentemente de matrizes, por exemplo). O PHP também suporta dois tipos compostos (não escalar): matrizes e objetos. Cada um desses valores podem ser definidos em uma variável ou retornados de uma função.

O PHP leva as expressões muito além, da mesma maneira que muitas outras linguagens fazem. O PHP é uma linguagem orientada a expressões, no sentido de que quase tudo são expressões. Considere o exemplo com o qual já lidamos, '$a = 5'. É fácil ver que há dois valores envolvidos aqui, o valor da constante inteira '5', e o valor de $a que está sendo atualizado para 5 também. Mas a verdade é que há um valor adicional envolvido aqui, e que é o próprio valor da atribuição. A própria atribuição é avaliada com o valor atribuído, neste caso 5. Na prática, significa que '$a = 5', independente do que faça, é uma expressão com o valor 5. Portanto, escrever algo como '$b = ($a = 5)' é como escrever '$a = 5; $b = 5;' (um ponto-e-vírgula marca o fim do comando). Como atribuições são analisadas da direita para a esquerda, você também pode escrever '$b = $a = 5'.

Outro bom exemplo de orientação de expressão é o pré e o pós-incremento e decremento. Usuários de PHP 2 e muitas outras linguagens podem estar familiarizados com a notação de variável++ e variable--. Este são operadores de incremento e decrimento. No PHP/FI 2, o comando '$a++' não tem valor (não é uma expressão), e portanto você não pode atribuir desta forma ou usá-la de jeito nenhum. O PHP evoluiu a capacidade de incremento/decremento criando estas expressões também, como em C. Em PHP, como em C, há dois tipos de incremento - pré-incremento e pós-incremento. Tanto o pré-incremento quanto o pós-incremento, essencialmente, incrementam as variáveis, e o efeito sobre a variável é idêntico. A diferença é com o valor da expressão de incremento. O pré-incremento, que é escrito '++$variavel', é avaliado como o valor de incremento (o PHP incrementa a variável antes de ler seu valor, por isso o nome pré-incremento). O pós-incremento, que é escrito '$variavel++' é avaliado como o valor original da variável, antes de ser incrementada (o PHP incrementa a variável depois de ler seu valor, por isso o nome 'pós-incremento').

Um tipo muito comum de expressões são expressões de comparação. Estas expressões avaliam para ser FALSE ou TRUE. O PHP suporta > (maior que), >= (maior ou igual a), == (igual), != (diferente), < (menor que) and <= (menor ou igual a). A linguagem também suporta um conjunto de operador de equivalencia estrita: === (igual a e do mesmo tipo) and !== (diferente de ou não do mesmo

Page 33: Php

tipo). Estas expressões são mais comumente usada dentro de execução condicional como comandos if.

O último exemplo de expressões com que nós vamos lidar aqui são as expressões combinadas operador-atribuição. Você já sabe que se você quer incrementar $a de 1, você só precisa escrever '$a++' ou '++$a'. Mas e se você quiser somar mais que um a ele, por exemplo 3? Você poderia escrever '$a++' várias vezes, mas esta obviamente não é uma forma muito eficiente ou confortável. Uma prática muito mais comum é escrever '$a = $a + 3'. '$a + 3' é avaliada como o valor de $a mais 3, e é atribuído de volta a $a, que resulta em incrementar $a de 3. Em PHP, como em várias outras linguagens como o C, você pode escrever isto de uma forma mais curta, que com o tempo se torna mais limpa e rápida de se entender também. Somar 3 ao valor corrente de $a pode ser escrito '$a +=3'. Isto significa exatamente "pegue o valor de $a, some 3 a ele, e atribua-o de volta a $a." Além de ser mais curto e mais limpo, isto também resulta em execução mais rápida. O valor de '$a += 3', como o valor de uma atribuição regular, é o valor atribuído. Note que NÃO é 3, mas o valor combinado de $a mais 3 (este é o valor que é atribuído a $a). Qualquer operador de dois parâmetros pode ser usado neste modo operador-atribuição, por exemplo '$a -= 5' (subtrai 5 do valor de $a), '$ b *= 7' (multiplica o valor de $b por 7), etc.

Há mais uma expressão que podem parecer estranha se você não a viu em outras linguagens, o operador condicional ternário:

<?php$primeira ? $segunda : $terceira?>

Se o valor da primeira sub-expressão é verdadeiro (TRUE, não-zero), então a segunda sub-expressão é avaliada, e este é o resultado da expressão condicional. Caso contrário, a terceira sub-expressão é avaliada e este é o valor.

O seguinte exemplo deve ajudá-lo a entender um pouco melhor pré e pós-incremento e expressões em geral:

<?phpfunction double($i){    return $i*2;}$b = $a = 5;        /* atribui o valor cinco às variáveis $a e $b */$c = $a++;          /* pós-incremento, atribui o valor original de $a                       (5) para $c */$e = $d = ++$b;     /* pré-incremento, atribui o valor incrementado de                       $b (6) a $d e $e */

/* neste ponto, tanto $d quanto $e são iguais a 6 */

$f = double($d++);  /* atribui o dobro do valor de $d antes                       do incremento, 2*6 = 12 a $f */$g = double(++$e);  /* atribui o dobro do valor de $e depois                       do incremento, 2*7 = 14 a $g */$h = $g += 10;      /* primeiro, $g é incrementado de 10 e termina com o                       valor 24. o valor da atribuição (24) é                       então atribuído a $h, e $h termina com o valor                       24 também. */?>

Page 34: Php

Algumas expressões podem ser consideradas instruções. Neste caso, uma instrução na forma 'expr' ';' ou seja, uma expressão seguida de um ponto e vírgula. Em '$b=$a=5;', $a=5 é uma expressão válida, mas não é um comando por si só. '$b=$a=5;' porém é um comando válido.

Uma última coisa que vale mencionar é o valor-verdade de expressões. Em muitos eventos, principalmente em instruções condicionais e loops, você não está interessado no valor específico da expressão, mas somente se ela significa TRUE ou FALSE (o PHP não tem um tipo booleano dedicado). As constantes TRUE e FALSE (insensitivas ao caso) são seus dois valores booleanos possíveis. As vezes uma expressão é automaticamente convertida para um booleano. Veja a seção sobre type-casting para detalhes de como isso é feito.

O PHP fornece uma implementação completa e poderosa de expressões, e a completa documentação dela vai além do escopo deste manual. Os exemplos acima devem dar a você uma boa idéia sobre o que são as expressões e como você pode construir expressões úteis. Através do restante do manual nós escreveremos expr ou expressao para indicar qualquer expressão PHP válida.

Operadores Constantes Mágicas

Last updated: Fri, 18 Jul 2008  

User Contributed Notes

Expressões phpsourcecode at blogspot dot com02-Jul-2008 06:37 The ternary conditional operator is a useful way of avoiding http://phpsourcecode.blogspot.com

inconvenient if statements.  They can even be used in the middle of a string concatenation, if you use parentheses.

Example:

if ( $wakka ) {  $string = 'foo' ;} else {  $string = 'bar' ;}

The above can be expressed like the following:

$string = $wakka ? 'foo' : 'bar' ;

If $wakka is true, $string is assigned 'foo', and if it's false, $string is assigned 'bar'.

To do the same in a concatenation, try:

$string = $otherString . ( $wakka ? 'foo' : 'bar' ) ; denzoo at gmail dot com16-Mar-2008 05:52 To jvm at jvmyers dot com:Your first two if statements just check if there's anything in the

Page 35: Php

string, if you wish to actually execute the code in your string you need eval(). jvm at jvmyers dot com24-Feb-2008 12:20 <?php// Compound booleans expressed as string args in an 'if' statement don't work as expected:////    Context://        1.  I generate an array of counters//        2.  I dynamically generate a compound boolean based on selected counters in the array//                Note: since the real array is sparse, I must use the 'empty' operator//        3.  When I submit the compound boolean as the expression of an 'if' statement, //            the 'if' appears to resolve ONLY the first element of the compound boolean.//    Conclusion: appears to be a short-circuiting issue

$aArray = array(1,0);

// Case 1: 'if' expression passed as string:

$sCondition = "!empty($aArray[0]) && !empty($aArray[1])";if ($sCondition){    echo "1. Conditions met<br />";}else{    echo "1. Conditions not met<br />";}

// Case 1 output:  "1. Conditions met"

// Case 2: same as Case 1, but using catenation operator

if ("".$sCondition.""){    echo "2. Conditions met<br />";}else{    echo "2. Conditions not met<br />";}

// Case 2 output:  "2. Conditions met"

// Case 3: same 'if' expression but passed in context:

if (!empty($aArray[0]) && !empty($aArray[1])){    echo "3. Conditions met<br />";}else{    echo "3. Conditions not met<br />";}

// Case 3 output:  "3. Conditions not met"

Page 36: Php

// [email protected]?>

PS: the bug folks say this "does not imply a bug in PHP itself."  Sure bugs me! petruzanauticoyahoo?com!ar20-Oct-2007 08:41 Regarding the ternary operator, I would rather say that the best option is to enclose all the expression in parantheses, to avoid errors and improve clarity:

<?php   print ( $a > 1 ? "many" : "just one" );?>

PS: for php, C++, and any other language that has it. winks71623-Aug-2007 01:42 reply to egonfreeman at gmail dot com04-Apr-2007 07:45

the second example u mentioned as follow:=====================================

$n = 3;$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

===========================================

everything works correctly but one sentence should be modified:

"from 3 * 3 into 3 * 4"  should be "from 3 * 3 into 4 * 3"

best regards~ :) george dot langley at shaw dot ca20-Jul-2007 11:01 Here's a quick example of Pre and Post-incrementation, in case anyone does feel confused (ref anonymous poster 31 May 2005)

<?PHPecho "Using Pre-increment ++\$a:<br>";$a = 1;echo "\$a = $a<br>";$b = ++$a;echo "\$b = ++\$a, so \$b = $b and \$a = $a<br>";echo "<br>";echo "Using Post-increment \$a++:<br>";$a = 1;echo "\$a = $a<br>";$b = $a++;echo "\$b = \$a++, so \$b = $b and \$a = $a<br>";?>

HTH

Page 37: Php

egonfreeman at gmail dot com04-Apr-2007 07:45 It is worthy to mention that:

$n = 3;$n * --$n

WILL RETURN 4 instead of 6.

It can be a hard to spot "error", because in our human thought process this really isn't an error at all! But you have to remember that PHP (as it is with many other high-level languages) evaluates its statements RIGHT-TO-LEFT, and therefore "--$n" comes BEFORE multiplying, so - in the end - it's really "2 * 2", not "3 * 2".

It is also worthy to mention that the same behavior will change:

$n = 3;$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

So, if you ever find yourself on a 'wild goose chase' for a bug in that "impossible-to-break, so-very-simple" piece of code that uses pre-/post-'s, remember this post. :)

(just thought I'd check it out - turns out I was right :P) shawnster14-Feb-2007 04:56 An easy fix (although intuitively tough to do...) is to reverse the comparison.

if (5 == $a) {}

If you forget the second '=', you'll get a parse error for trying to assign a value to a non-variable. nabil_kadimi at hotmail dot com29-Jan-2007 07:46 Attention! php will not warn you if you write (1) When you mean (2)

(1)<?if($a=0)     echo "condition is true";else     echo "condition is false";//output: condition is false?>

(2)<?if($a==0)     echo "condition is true";else     echo "condition is false";//output: condition is true?>

Page 38: Php

richard at phase4 dot ie19-Jan-2006 12:00 Follow up on Martin K. There are no hard and fast rules regarding operator precedence. Newbies should definitely learn them, but if their use results in code that is not easy to read you should use parentheses. The two important things are that it works properly AND is maintainable by you and others. Martin K20-Oct-2005 06:28 At 04-Feb-2005 05:13, tom at darlingpet dot com said:> It's also a good idea to use parenthesis when using something SIMILAR to:> > <?php> echo (trim($var)=="") ? "empty" : "not empty";> ?>

No, it's a BAD idea.

All the short-circuiting operators, including the ternary conditional operator, have LOWER precedence than the comparison operators, so they almost NEVER need parentheses around their subexpressions.

Inserting the parentheses suggested above does not change the meaning of the code, but their use misleads inexperienced programmers to expect that things like this will work in a similar manner:

<?phpfunction my_print($a) { print($a); }my_print (trim($var)=="") ? "empty" : "not empty";?>

when of course it doesn't.

Rather than worrying that code doesn't work as expected, simply learn the precedence rules (http://www.php.net/manual/en/language.operators.php) so that one expects the right things. stochnagara at hotmail dot com19-Aug-2005 05:06 12345alex at gmx dot net 's case is actually handled by the === operator. That's what he needs.

There is also another widely used function. I call it myself is_nil which is true for NULL,FALSE,array() and '', but not for 0 and "0".

function is_nil ($value) { return !$value && $value !== 0 && $value !== '0';}

Another useful function is "get first argument if it is not empty or get second argument otherwise". The code is:

function def ($value, $defaultValue) { return is_nil ($value) ? $defaultValue : $value;} 12345alex at gmx dot net14-Aug-2005 07:00 this code:    print array() == NULL ? "True" : "False";    print " (" . (array() == NULL) . ")\n";

Page 39: Php

    $arr = array();    print array() == $arr ? "True" : "False";    print " (" . (array() == $arr) . ")\n";

    print count(array()) . "\n";    print count(NULL) . "\n";

will output (on php4 and php5):    True (1)    True (1)    0    0

so to decide wether i have NULL or an empty array i will also have to use gettype(). this seems some kind of weird for me, although if is this is a bug, somebody should have noticed it before.

alex sabinx at gmail dot com26-Jun-2005 11:25 Pre- and Post-Incrementation, I believe, are important to note and in the correct place. The section deals with the value of an expression. ++$a and $a++ have different values, and both forms have valid uses.

And, because it can be confusing, it is that much more important to note. Although it could be worded better, it does belong. 31-May-2005 12:07 I don't see why it is necessary here to explain pre- and post- incrementing.

This is something that will confuse new users of PHP, even longer time programmers will sometimes miss a the fine details of a construct like that.

If something has a side-effect it should be on a line of it's own, or at least be an expression of it's own and not part of an assignment, condition or whatever. tom at darlingpet dot com04-Feb-2005 02:13 Something I've noticed with ternary expressions is if you do something like :

<?= $var=="something" ? "is something" : "not something"; ?>

It will give wacky results sometimes...

So be sure to enclose the ternary expression in parenthesis when ever necessary (such as having multiple expressions or nested ternary expressions)

The above could look like:

<?= ($var=="something") ? "is something" : "not something"; ?>

It's also a good idea to use parenthesis when using something SIMILAR to:

<?phpecho (trim($var)=="") ? "empty" : "not empty";?>

Page 40: Php

In some cases other than the <?= ?> example, not placing the entire expression in appropriate parenthesis might yield undesirable results as well.. but I'm not quite sure. stian at datanerd dot net25-Feb-2003 02:37 The short-circuit feature is indeed intended, and there are two types of evaluators, those who DO short-circuit, and those who DON'T, || / && and | / & respectively.The latter method is the bitwise operators, but works great with the usual boolean values ( 0/1 )

So if you don't want short-circuiting, try using the | and & instead.

Read more about the bitwise operators here:http://www.php.net/manual/en/language.operators.bitwise.php oliver at hankeln-online dot de07-Aug-2002 06:06 The short-circuiting IS a feature. It is also available in C, so I suppose the developers won�t remove it in future PHP versions.

It is rather nice to write:

$file=fopen("foo","r") or die("Error!");

Greets,Oliver php at cotest dot com17-Jul-2002 11:08 It should probably be mentioned that the short-circuiting of expressions (mentioned in some of the comments above) is often called "lazy evaluation" (in case someone else searches for the term "lazy" on this page and comes up empty!). Mattias at mail dot ee25-May-2002 03:29 A note about the short-circuit behaviour of the boolean operators.

1. if (func1() || func2())Now, if func1() returns true, func2() isn't run, since the expressionwill be true anyway.

2. if (func1() && func2())Now, if func1() returns false, func2() isn't run, since the expressionwill be false anyway.

The reason for this behaviour comes probably from the programminglanguage C, on which PHP seems to be based on. There theshort-circuiting can be a very useful tool. For example:

int * myarray = a_func_to_set_myarray(); // init the arrayif (myarray != NULL && myarray[0] != 4321) // check    myarray[0] = 1234;

Now, the pointer myarray is checked for being not null, then thecontents of the array is validated. This is important, because ifyou try to access an array whose address is invalid, the programwill crash and die a horrible death. But thanks to the shortcircuiting, if myarray == NULL then myarray[0] won't be accessed,and the program will work fine. yasuo_ohgaki at hotmail dot com11-Mar-2001 11:14

Page 41: Php

Manual defines "expression is anything that has value", Therefore, parser will give error for following code.

($val) ? echo('true') : echo('false'); Note: "? : " operator has this syntax  "expr ? expr : expr;"

since echo does not have(return) value and ?: expects expression(value).

However, if function/language constructs that have/return value, such as include(), parser compiles code.

Note: User defined functions always have/return value without explicit return statement (returns NULL if there is no return statement). Therefore, user defined functions are always valid expressions. [It may be useful to have VOID as new type to prevent programmer to use function as RVALUE by mistake]

For example,

($val) ? include('true.inc') : include('false.inc');

is valid, since "include" returns value.

The fact "echo" does not return value(="echo" is not a expression), is less obvious to me.

Print() and Echo() is NOT identical since print() has/returns value and can be a valid expression. anthony at n dot o dot s dot p dot a dot m dot trams dot com24-Nov-2000 11:01 The ternary conditional operator is a useful way of avoiding inconvenient if statements.  They can even be used in the middle of a string concatenation, if you use parentheses. 

Example:

if ( $wakka ) {   $string = 'foo' ; } else {   $string = 'bar' ; }

The above can be expressed like the following:

$string = $wakka ? 'foo' : 'bar' ;

If $wakka is true, $string is assigned 'foo', and if it's false, $string is assigned 'bar'.

To do the same in a concatenation, try:

$string = $otherString . ( $wakka ? 'foo' : 'bar' ) ;

Page 42: Php

Listar

<?php

//ARQUIVO TXT

$arquivo = “usuarios.txt”;

//Abri a conexao com o banco de dados

$conexao = mysql_connect(”localhost”, “root”, “”);

mysql_select_db(”bancoteste”);

//ABRIR O ARQUIVO TXT

$arquivo = fopen($arquivo, “w”);

Page 43: Php

//Faz a consulta no banco de dados

$result = mysql_query(”select * from usuarios”);

while($escrever = mysql_fetch_array($result)){

 

 $conteudo = “\r\n” . $escrever['login'];

 $conteudo .= “\t” . $escrever['nome'];

 //ESCREVE NO ARQUIVO TXT

 fwrite($arquivo, $conteudo);

}

//FECHA O ARQUIVO

fclose($arquivo);

//Fecha a conexão

mysql_close($conexao);

?>

<a href=”usuarios.txt” title=”usuários.txt”>Usuários.txt</a>

Segue o arquivo txt