<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog do Beraldo &#187; Programação</title>
	<atom:link href="http://www.rberaldo.com.br/blog/tag/programacao/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rberaldo.com.br/blog</link>
	<description>Programação, Música, Entretenimento e o que mais me vier à mente</description>
	<lastBuildDate>Mon, 06 Feb 2012 14:30:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<item>
		<title>Curso de Shell Script &#8211; Módulo #1: Scripts Shell e suas estruturas</title>
		<link>http://www.rberaldo.com.br/blog/curso-de-shell-script-modulo-1-scripts-shell-estruturas/</link>
		<comments>http://www.rberaldo.com.br/blog/curso-de-shell-script-modulo-1-scripts-shell-estruturas/#comments</comments>
		<pubDate>Sat, 05 Nov 2011 20:44:59 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Shell Script (Bash)]]></category>
		<category><![CDATA[Bash]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[sh]]></category>
		<category><![CDATA[Shell]]></category>
		<category><![CDATA[unix]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=478</guid>
		<description><![CDATA[(Caso não tenha lido a primeira parte (módulo #0), veja-a aqui: http://www.rberaldo.com.br/blog/curso-shell-script-comandos-basicos-linux/) Inicialmente, eu separaria este texto em vários módulos. Porém, optei por faer algo mais sucinto e criar apenas este módulo &#8211; que complementa o Módulo #0, sobre os comandos básicos do Linux. Neste módulo, serão abordados vários temas da programação em Shell (Bash), [...]]]></description>
			<content:encoded><![CDATA[<p>(Caso não tenha lido a primeira parte (módulo #0), veja-a aqui: <a href="http://www.rberaldo.com.br/blog/curso-shell-script-comandos-basicos-linux/">http://www.rberaldo.com.br/blog/curso-shell-script-comandos-basicos-linux/</a>)</p>
<p>Inicialmente, eu separaria este texto em vários módulos. Porém, optei por faer algo mais sucinto e criar apenas este módulo &#8211; que complementa o Módulo #0, sobre os comandos básicos do Linux.</p>
<p>Neste módulo, serão abordados vários temas da programação em Shell (Bash), desde variáveis e funções, até expansões, expressões regulares etc.</p>
<p>Sem mais delongas, vamos ao que interessa! :)</p>
<p><span id="more-478"></span></p>
<h3>Sumário</h3>
<p><a href="#scripts">0. Scripts Shell</a><br />
<a href="#vars">1. Variáveis</a><br />
<a href="#envvars">1.1 Variáveis de Ambiente</a><br />
<a href="#espvars">1.2. Variáveis Especiais</a><br />
<a href="#fluxo">2. Controle de Fluxo</a><br />
<a href="#cond">2.1. Condicionais</a><br />
<a href="#if">2.1.1. if</a><br />
<a href="#case">2.1.2. case</a><br />
<a href="#select">2.1.3. select</a><br />
<a href="#repeat">2.2. Estruturas de Repetição (Loops)</a><br />
<a href="#for">2.2.1. for</a><br />
<a href="#while">2.2.2. while</a><br />
<a href="#until">2.2.3. until&#8230;do</a><br />
<a href="#break">2.2.4. break</a><br />
<a href="#continue">2.2.5. continue</a><br />
<a href="#cpattern">3. Padrão C/C++ em Expressões &#8220;(())&#8221;</a><br />
<a href="#es">4. Entrada/Saída</a><br />
<a href="#redir">4.1. Redirecionamento</a><br />
<a href="#pipe">4.2. Usando Pipelines</a><br />
<a href="#expansoes">5. Expansões</a><br />
<a href="#varexp">5.1. Expansão de Variáveis</a><br />
<a href="#params">6. Parâmetros de linha de comando</a><br />
<a href="#funcs">7. Definindo Funções</a><br />
<a href="#return">7.1. Retorno de Funções</a><br />
<a href="#er">8. Expressões Regulares em Bash</a><br />
<a href="#mathexp">9. Expressões Matemáticas</a><br />
<a href="#bashrc">10. O Arquivo .bashrc</a><br />
<a href="#alias">11. Aliases (Apelidos)</a><br />
<a href="#refs">12. Referências</a></p>
<h3><a name="scripts">0. Scripts Shell</a></h3>
<p>Antes de mostrar os recursos do shell, vamos dar uma olhada na maneira como devemos criar scripts shell. Isso facilitará a compreensão do restante do artigo.</p>
<p>Todo arquivo com códigos shell deve ter, na primeira linha, o identificador do interpretador a ser utilizado. A &#8220;linha mágica&#8221; que chama o interpretado bash é:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span></pre></div></div>

<p>O mesmo vale para outras linguagens interpretadas, como PHP, Python, Ruby, Perl etc.</p>
<p>Tendo essa linha no início do arquivo, o segundo passo é dar permissão de execução ao arquivo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">chmod</span> +x script.sh
<span style="color: #000000; font-weight: bold;">&lt;</span>pre<span style="color: #000000; font-weight: bold;">&gt;</span>
&nbsp;
Feito isso, basta executar o script:
&nbsp;
<span style="color: #000000; font-weight: bold;">&lt;</span>pre <span style="color: #007800;">lang</span>=<span style="color: #ff0000;">&quot;bash&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span>
$ .<span style="color: #000000; font-weight: bold;">/</span>script.sh</pre></div></div>

<p>Também é possível executar o script usando o comando <strong>bash</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">bash</span> script.sh</pre></div></div>

<p>Assim não é necessário haver a &#8220;linha mágica&#8221; no início do script. Também não é preciso dar permissão de execução ao arquivo.</p>
<h3><a name="vars">1. Variáveis</a></h3>
<p>O Bash, assim como muitas outras linguagens, possui o conceito de variável. Para definir uma variável:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">nome_da_variavel</span>=<span style="color: #ff0000;">&quot;valor da variável&quot;</span></pre></div></div>

<p>É importante ressaltar que não deve haver espaços entre o símbolo de atribuição, o nome da variável e seu valor, para que o bash interprete o comando como atribuição, não chamada de comandos.</p>
<p>Para exibir o valor de uma variável, basta usar <strong>echo</strong> da seguinte forma:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$nome_da_variavel</span></pre></div></div>

<h4><a name="envvars">1.1 Variáveis de Ambiente</a></h4>
<p>As variáveis de ambiente são aquelas conhecidas pelos demais processos (programas em execução). Exemplos destas variáveis são: HOME, PATH, EDITOR, etc.</p>
<p>Para entender o seu uso, vejamos um exemplo: editores de texto, como <strong>Vi</strong>, possuem diferentes interfaces para os modos texto e gráfico e necessitam saber qual o tipo de terminal o usuário está usando. A variável de ambiente TERM é o modo pelo qual isto pode ser determinado. Outro exemplo são os programas de e-mail que permitem ao usuário editar mensagens com o editor de textos de sua preferência. Como estes programas sabem qual editor usar? É através da variável EDITOR ou VISUAL.</p>
<p>Qualquer variável pode se tornar uma variável de ambiente. Para isto, ela deve ser &#8220;exportada&#8221;, com o comando <strong>export</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #000000; font-weight: bold;">&lt;</span>variável<span style="color: #000000; font-weight: bold;">&gt;</span></pre></div></div>

<p>Também podemos exportar e atribuir valores a uma variável numa única linha de comando:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #000000; font-weight: bold;">&lt;</span>variável<span style="color: #000000; font-weight: bold;">&gt;</span>=<span style="color: #000000; font-weight: bold;">&lt;</span>valor<span style="color: #000000; font-weight: bold;">&gt;</span></pre></div></div>

<p>Podemos verificar quais são as variáveis de ambiente já definidas e seus respectivos valores usando o comando abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #660033;">-p</span></pre></div></div>

<p>Para visualizar todas as variáveis basta usar set ou env. Uma importante variável de ambiente é PATH que ajuda o shell a encontrar os comandos que o usuário executa. Todo comando executado é, na realidade, um arquivo. Estes arquivos são chamados executáveis e estão armazenados em vários diretórios como /bin ou /usr/bin. O valor da variável PATH é uma lista de diretórios em que o shell procura toda vez que executamos um comando cujo arquivo não é encontrado no diretório corrente. Assim, não precisamos alterar o diretório de trabalho todas vez que necessitamos executar um comando que se encontra em outro diretório. Basta acrescentar o diretório que contém tal comando à variável PATH. Os nomes dos diretórios na variável são separados pelo caractere dois-pontos (:).</p>
<p>Caso o usuário joao queira adicionar um outro diretório, digamos /home/joao/bin à variável PATH, deve proceder como mostrado a seguir:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #7a0874; font-weight: bold;">export</span> <span style="color: #007800;">PATH</span>=<span style="color: #007800;">$PATH</span>:<span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>joao<span style="color: #000000; font-weight: bold;">/</span>bin   <span style="color: #666666; font-style: italic;"># adiciona o diretório</span>
$ <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$PATH</span>                         <span style="color: #666666; font-style: italic;"># verifica</span>
<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>joao<span style="color: #000000; font-weight: bold;">/</span>bin</pre></div></div>

<p>O primeiro comando faz com que a variável receba o seu valor atual, concatenado com o nome do diretório a ser acrescentado. Observe que existe um &#8220;:&#8221; antes do nome do diretório. O segundo comando é utilizado apenas para visualizarmos o resultado do primeiro.</p>
<h4><a name="espvars">1.2. Variáveis Especiais</a></h4>
<p>Existem algumas variáveis especiais, normalmente utilizadas em script shell, para verificação de parâmetros, valores de retorno de comandos e funções etc.</p>
<table width="100%">
<thead>
<tr>
<td>Variável</td>
<td>Descrição</td>
</tr>
</thead>
<tbody>
<tr>
<td>$0</td>
<td>Parâmetro número 0 (nome do comando ou função)</td>
</tr>
<tr>
<td>$1</td>
<td>Parâmetro número 1 (da linha de comando ou função)</td>
</tr>
<tr>
<td>&#8230;</td>
<td>Parâmetro número N &#8230;</td>
</tr>
<tr>
<td>$9</td>
<td>Parâmetro número 9 (da linha de comando ou função)</td>
</tr>
<tr>
<td>${10}</td>
<td>Parâmetro número 10 (da linha de comando ou função)</td>
</tr>
<tr>
<td>$#</td>
<td>Número total de parâmetros da linha de comando ou função</td>
</tr>
<tr>
<td>$*</td>
<td>Todos os parâmetros, como uma string única</td>
</tr>
<tr>
<td>$@</td>
<td>Todos os parâmetros, como várias strings protegidas</td>
</tr>
<tr>
<td>$$</td>
<td>Número PID do processo atual (do próprio script)</td>
</tr>
<tr>
<td>$!</td>
<td>Número PID do último processo em segundo plano</td>
</tr>
<tr>
<td>$_</td>
<td>Último argumento do último comando executado</td>
</tr>
<tr>
<td>$?</td>
<td>Valor de retorno do último comando executado</td>
</tr>
</tbody>
</table>
<h3><a name="fluxo">2. Controle de Fluxo</a></h3>
<p>Controle de fluxo permite interromper, continuar e deslocar o fluxo de execução do script. Isso envolve controles de decisão (condicionais) e estruturas de repetição (loops).</p>
<h4><a name="cond">2.1. Condicionais</a></h4>
<h4><a name="if">2.1.1. if</a></h4>
<p>Sintaxe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">if</span> <span style="color: #000000; font-weight: bold;">&lt;</span>condicao<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #000000; font-weight: bold;">then</span>
    comandos
<span style="color: #000000; font-weight: bold;">elif</span> <span style="color: #000000; font-weight: bold;">&lt;</span>condicao_2<span style="color: #000000; font-weight: bold;">&gt;</span>
    comandos 
<span style="color: #000000; font-weight: bold;">else</span>
    comandos 
<span style="color: #000000; font-weight: bold;">fi</span></pre></div></div>

<p>O <strong>if</strong>, ao contrário do que ocorre em muitas outras linguagens, testa o retorno de um comando, não uma expressão.</p>
<p>Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">test</span> <span style="color: #000000;">5</span> <span style="color: #660033;">-lt</span> <span style="color: #000000;">7</span>
<span style="color: #000000; font-weight: bold;">then</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'5 é menor que 7'</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></div></div>

<p>Porém, é possível posicionar a expressão entre colchetes, de forma a tornar o if mais parecido com o que acontece em outras linguagens:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #000000;">5</span> <span style="color: #660033;">-lt</span> <span style="color: #000000;">7</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #000000; font-weight: bold;">then</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'5 é menor que 7'</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></div></div>

<p>O &#8220;-lt&#8221; significa &#8220;<em>less than</em>&#8220;, ou seja, &#8220;<em>menor que</em>&#8220;, equivalendo ao operador &#8220;<".</p>
<p>Outros possíveis operadores são:</p>
<p><strong>Comparação Numérica</strong><br />
-lt: É menor que (LessThan)<br />
-gt: É maior que (GreaterThan)<br />
-le: É menor igual (LessEqual)<br />
-ge: É maior igual (GreaterEqual)<br />
-eq: É igual (EQual)<br />
-ne: É diferente (NotEqual)</p>
<p><strong>Comparação de Strings</strong><br />
=: É igual<br />
!=: É diferente<br />
-n: É não nula (não vazia)<br />
-z: É nula (vazia)</p>
<p><strong>Operadores Lógicos</strong><br />
!: NÃO lógico (NOT)<br />
-a: E lógico (AND)<br />
-o: OU lógico (OR)</p>
<p><strong>Testes em arquivos</strong><br />
-b: É um dispositivo de bloco<br />
-c: É um dispositivo de caractere<br />
-d: É um diretório<br />
-e: O arquivo existe<br />
-f: É um arquivo normal<br />
-g: O bit SGID está ativado<br />
-G: O grupo do arquivo é o do usuário atual<br />
-k: O sticky-bit está ativado<br />
-L: O arquivo é um link simbólico<br />
-O: O dono do arquivo é o usuário atual<br />
-p: O arquivo é um named pipe<br />
-r: O arquivo tem permissão de leitura<br />
-s: O tamanho do arquivo é maior que zero<br />
-S: O arquivo é um socket<br />
-t: O descritor de arquivos N é um terminal<br />
-u: O bit SUID está ativado<br />
-w: O arquivo tem permissão de escrita<br />
-x: O arquivo tem permissão de execução<br />
-nt: O arquivo é mais recente (NewerThan)<br />
-ot: O arquivo é mais antigo (OlderThan)<br />
-ef: O arquivo é o mesmo (EqualFile)</p>
<h4><a name="case">2.1.2. case</a></h4>
<p>Sintaxe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">case</span> <span style="color: #000000; font-weight: bold;">&lt;</span>string<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">in</span>
    opcao1<span style="color: #7a0874; font-weight: bold;">&#41;</span>
        comandos 
        <span style="color: #000000; font-weight: bold;">;;</span>
    opcao2<span style="color: #7a0874; font-weight: bold;">&#41;</span>
        comandos 
        <span style="color: #000000; font-weight: bold;">;;</span>
    <span style="color: #000000; font-weight: bold;">*</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
        operação padrão
<span style="color: #000000; font-weight: bold;">esac</span></pre></div></div>

<p>Exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Digite um número&quot;</span>
<span style="color: #c20cb9; font-weight: bold;">read</span> x
&nbsp;
<span style="color: #000000; font-weight: bold;">case</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$x</span>&quot;</span> <span style="color: #000000; font-weight: bold;">in</span> 
    <span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Você digitou o número 1&quot;</span>
        <span style="color: #000000; font-weight: bold;">;;</span>
    <span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Você digitou o número 2&quot;</span>
        <span style="color: #000000; font-weight: bold;">;;</span>
    <span style="color: #000000; font-weight: bold;">*</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Você digitou outro número&quot;</span>
<span style="color: #000000; font-weight: bold;">esac</span></pre></div></div>

<h4><a name="select">2.1.3. select</a></h4>
<p>Sintaxe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">select</span> <span style="color: #000000; font-weight: bold;">&lt;</span>variavel<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">&lt;</span>opcao1<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">&lt;</span>opcao2<span style="color: #000000; font-weight: bold;">&gt;</span> ...
<span style="color: #000000; font-weight: bold;">do</span> 
    comandos 
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>O comando <strong>select</strong> é pouco utilizado, mas pode ser muito útil para montar menus. Esse comando exibe um menu, associando cada opção a um número. Quando o usuário seleciona o número da opção, o seu valor é associado à <variavel>.</p>
<p>Exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">select</span> i <span style="color: #000000; font-weight: bold;">in</span> lista_arquivos lista_arquivos_tree
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #000000; font-weight: bold;">case</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$i</span>&quot;</span> <span style="color: #000000; font-weight: bold;">in</span> 
        lista_arquivos<span style="color: #7a0874; font-weight: bold;">&#41;</span>
            <span style="color: #c20cb9; font-weight: bold;">ls</span>
            <span style="color: #000000; font-weight: bold;">;;</span>
        lista_arquivos_tree<span style="color: #7a0874; font-weight: bold;">&#41;</span>
            <span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-R</span>
            <span style="color: #000000; font-weight: bold;">;;</span>
    <span style="color: #000000; font-weight: bold;">esac</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<h4><a name="repeat">2.2. Estruturas de Repetição (Loops)</a></h3>
<p>Loops são estruturas que permitem fazer iterações sobre algum dado.</p>
<h4><a name="for">2.2.1. for</a></h4>
<p>Sintaxe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> <span style="color: #000000; font-weight: bold;">&lt;</span>var<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">&lt;</span>lista<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #000000; font-weight: bold;">&lt;</span>comandos<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>&#8220;var&#8221; é o nome da variável a ser usada no bloco de repetição. &#8220;lista&#8221; pode ser uma lista de dados, fixa ou retornada por outro comando (como o ls), uma sequência de números etc.</p>
<p>Exemplos:</p>
<p>Exibe uma sequência de números:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> i <span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000;">1</span> <span style="color: #000000;">2</span> <span style="color: #000000;">3</span> <span style="color: #000000;">4</span> <span style="color: #000000;">5</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Lista os diretórios e arquivos da raiz do sistema de arquivos:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> i <span style="color: #000000; font-weight: bold;">in</span> $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> i <span style="color: #000000; font-weight: bold;">in</span> $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #c20cb9; font-weight: bold;">seq</span> <span style="color: #000000;">1</span> <span style="color: #000000;">10</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> i <span style="color: #000000; font-weight: bold;">in</span> $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">passwd</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<h4><a name="while">2.2.2. while</a></h4>
<p>Sintaxe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">while</span> <span style="color: #000000; font-weight: bold;">&lt;</span>condicao<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #000000; font-weight: bold;">&lt;</span>comandos<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Exemplos:</p>
<p>Exibe a sequência de 1 a 10:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">i</span>=<span style="color: #000000;">0</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$i</span> <span style="color: #660033;">-lt</span> <span style="color: #000000;">10</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
    <span style="color: #007800;">i</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>i+<span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Loop infinito que exibe &#8220;bash&#8221; na tela:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'bash'</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Lendo strings da entrada padrão:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">read</span> i
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'Voce digitou a string: '</span> <span style="color: #007800;">$i</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Exibe as linhas de um arquivo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #ff0000;">'arquivo.txt'</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">read</span> i
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Esse exemplo facilita o trabalho com arquivos de texto, cujas linhas possuem espaços. Se fosse usado um loop for nesse caso, seria necessário alterar a variável de ambiente IFS, definindo o separador para quebra de linha (\n).</p>
<p>Uma variação do exemplo anterior é esta:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">read</span> i
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
<span style="color: #000000; font-weight: bold;">done</span> <span style="color: #000000; font-weight: bold;">&lt;</span> arquivo.txt</pre></div></div>

<p>A principal diferença entre estes dois últimos exemplos é que, no primeiro, o loop while é executado num subshell, devido ao uso do pipe (|). No segundo exemplo, o while é executado no shell corrente.</p>
<p>Para ilustrar o problema, crie um arquivo chamado &#8220;arq.txt&#8221; com algumas linhas de texto. Crie este script e execute-o:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #007800;">FILE</span>=<span style="color: #ff0000;">'arq.txt'</span>
&nbsp;
<span style="color: #007800;">total</span>=<span style="color: #000000;">0</span>
<span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #007800;">$FILE</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">read</span> i
<span style="color: #000000; font-weight: bold;">do</span>
	<span style="color: #007800;">total</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>total+<span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'Total de linhas: '</span> <span style="color: #007800;">$total</span>
&nbsp;
<span style="color: #007800;">total</span>=<span style="color: #000000;">0</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">read</span> i
<span style="color: #000000; font-weight: bold;">do</span>
	<span style="color: #007800;">total</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>total+<span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span> <span style="color: #000000; font-weight: bold;">&lt;</span> <span style="color: #007800;">$FILE</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'Total de linhas: '</span> <span style="color: #007800;">$total</span></pre></div></div>

<p>O primeiro loop é executado num subshell, fazendo com que a variável &#8220;total&#8221;, usada no corpo do loop, existe apenas nesse subshell. No segundo caso, isso não ocorre. Isso pode gerar grandes dores de cabeça&#8230; (como já ocorreu comigo)</p>
<h4><a name="until">2.2.3. until&#8230;do</a></h4>
<p>Sintaxe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">until</span> <span style="color: #000000; font-weight: bold;">&lt;</span>condicao<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #000000; font-weight: bold;">&lt;</span>comandos<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Nesse loop, a condição é oposta à usada no while. Por exemplo:</p>
<p>Com while:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">i</span>=<span style="color: #000000;">0</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$i</span> <span style="color: #660033;">-lt</span> <span style="color: #000000;">10</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
    <span style="color: #007800;">i</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>i+<span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Com unitl:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">i</span>=<span style="color: #000000;">0</span>
<span style="color: #000000; font-weight: bold;">until</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$i</span> <span style="color: #660033;">-ge</span> <span style="color: #000000;">10</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
    <span style="color: #007800;">i</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>i+<span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>Para fazer a mesma coisa, tivemos que usar expressões diferentes na condição do loop. </p>
<h4><a name="break">2.2.4. break</a></h4>
<p>O comando break encerra um loop imediatamente.</p>
<p>Exemplos:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">i</span>=<span style="color: #000000;">0</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$i</span> <span style="color: #660033;">-ge</span> <span style="color: #000000;">10</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>
    <span style="color: #000000; font-weight: bold;">then</span>
        <span style="color: #7a0874; font-weight: bold;">break</span>
    <span style="color: #000000; font-weight: bold;">fi</span>
    <span style="color: #007800;">i</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>i+<span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">while</span> <span style="color: #c20cb9; font-weight: bold;">read</span> i
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #007800;">$i</span> <span style="color: #660033;">-eq</span> <span style="color: #000000;">0</span> <span style="color: #7a0874; font-weight: bold;">&#93;</span>
    <span style="color: #000000; font-weight: bold;">then</span>
        <span style="color: #7a0874; font-weight: bold;">break</span>
    <span style="color: #000000; font-weight: bold;">fi</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<h4><a name="continue">2.2.5. continue</a></h4>
<p>O comando continue para a execução da iteração corrente e vai para a próxima iteração, mesmo que haja mais comandos no bloco de repetição.</p>
<h3><a name="cpattern">3. Padrão C/C++ em Expressões &#8220;(())&#8221;</a></h3>
<p>É possível usar o padrão C em expressões do shell, como em condicionais de estruturas de controle. Para isso, basta colocar a expressão entre dois parênteses. </p>
<p>Exemplos;</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">i</span>=<span style="color: #000000;">0</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span> i <span style="color: #000000; font-weight: bold;">&lt;</span> <span style="color: #000000;">10</span> <span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
    <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>i++<span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<p>É possível, inclusive, usar o padrão do loop for do C:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>i = <span style="color: #000000;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> <span style="color: #000000;">10</span>; i++<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">do</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$i</span>
<span style="color: #000000; font-weight: bold;">done</span></pre></div></div>

<h3><a name="es">4. Entrada/Saída</a></h3>
<p>Existem três dispositivos principais, que sempre estão abertos, que merecem destaque:</p>
<p>stdin (standard input): entrada padrão. Corresponde, em geral, ao teclado;<br />
stdout (standard output): saída padrão. Corresponde, em geral, à tela do terminal;<br />
stderr (standard error): saída padrão de erros. Corresponde, em geral, à tela do terminal, também.</p>
<p>Esses três dispositivos estão em /dev e estão sempre disponíveis. Quem programa em C, sabe muito bem disso, pois já deve ter usado stdin, stdout e stderr junto com fprintf, fread, fwrite e semelhantes; esses três dispositivos comportam-se como arquivos comuns, sempre abertos e que não devem ser fechados.<br />
É possível brincar com eles no próprio shell. Experimentem dar um cat em /dev/stdin para ver o que acontece. :)</p>
<h4><a name="redir">4.1. Redirecionamento</a></h4>
<p>A entrada de um programa consiste nos dados que lhe são passados inicialmente, os quais são necessários para a execução do programa. A entrada de um programa pode vir do teclado ou de um arquivo, por exemplo. Argumentos passados à comandos constituem a sua entrada.<br />
A saída é constituída pelas informações geradas pelo programa, ou seja, o resultado de sua execução. A saída pode ser mostrada na tela ou gravada em um arquivo de registro.</p>
<p>Muitos comandos do Linux têm sua entrada configurada para a entrada padrão e sua saída para a saída padrão. A entrada padrão é o teclado e a saída padrão é o monitor. Vejamos um exemplo usando o comando cat, que lê dados de todos os arquivos passados como parâmetros e os envia diretamente para a saída padrão. Usando o comando abaixo, veremos o conteúdo do arquivo &#8220;arq1&#8243; seguido pelo conteúdo de &#8220;arq2&#8243;.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">cat</span> arq1 arq2</pre></div></div>

<p>Entretanto, se nenhum nome de arquivo for dado como parâmetro, o comando cat lê dados da entrada padrão e os envia para a saída padrão. Para interromper, deve-se pressionar as teclas ctrl e d simultaneamente (ctrl+d).</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">cat</span> 
Ola<span style="color: #000000; font-weight: bold;">!</span> Tem alguem ai?  <span style="color: #666666; font-style: italic;"># usuário </span>
Ola<span style="color: #000000; font-weight: bold;">!</span> Tem alguem ai?  <span style="color: #666666; font-style: italic;"># eco do sistema </span>
Ate mais<span style="color: #000000; font-weight: bold;">!</span>            <span style="color: #666666; font-style: italic;"># usuário </span>
Ate mais<span style="color: #000000; font-weight: bold;">!</span>            <span style="color: #666666; font-style: italic;"># eco do sistema</span>
              <span style="color: #666666; font-style: italic;"># usuário pressiona ctrl+d</span></pre></div></div>

<p>Como podemos ver, cada linha que o usuário digita é imediatamente ecoada pelo comando cat. Aqui um outro exemplo: o comando sort lê dados da entrada padrão &#8211; a menos que algum arquivo seja dado como parâmetro &#8211; e ordena os dados, enviando-os para a saída padrão:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">sort</span> 
bananas     <span style="color: #666666; font-style: italic;"># usuário</span>
peras       <span style="color: #666666; font-style: italic;"># usuário</span>
goiabas     <span style="color: #666666; font-style: italic;"># usuário</span>
            <span style="color: #666666; font-style: italic;"># ctrl+d</span>
bananas     <span style="color: #666666; font-style: italic;"># eco do sistema</span>
goiabas     <span style="color: #666666; font-style: italic;"># eco do sistema</span>
peras       <span style="color: #666666; font-style: italic;"># eco do sistema</span></pre></div></div>

<p>Digamos que queremos enviar a saída do comando sort para um arquivo, gravando os dados digitados anteriormente. O shell nos permite redirecionar a saída para um arquivo usando o símbolo &#8220;>&#8221;.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">sort</span> <span style="color: #000000; font-weight: bold;">&gt;</span> lista
bananas  <span style="color: #666666; font-style: italic;"># usuário</span>
peras    <span style="color: #666666; font-style: italic;"># usuário</span>
goiabas  <span style="color: #666666; font-style: italic;"># usuário</span>
         <span style="color: #666666; font-style: italic;"># ctrl+d</span></pre></div></div>

<p>Como se pode ver, o resultado do comando sort não é mostrado imediatamente após o se digitar ctrl+d. Ao invés disso, é salvo em um arquivo chamado &#8220;lista&#8221;. Vejamos o conteúdo desse arquivo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">cat</span> lista
bananas
goiabas
peras</pre></div></div>

<p>Com o redirecionamento de saída, temos uma maneira simples de criar arquivos de texto. Para isso, utilizamos o comando cat para ler a entrada padrão (teclado) e redirecionamos sua saída para um arquivo.</p>
<p>Ao usar &#8220;>&#8221; para redirecionar a saída para um arquivo, estamos realizando um redirecionamento destrutivo, ou seja, o comando &#8220;ls > lista&#8221; sobrescreve o conteúdo do arquivo &#8220;lista&#8221;. Isto é equivalente a dizer que todo o conteúdo anterior de &#8220;lista&#8221; é apagado.<br />
Se, ao invés disso, redirecionarmos usando &#8220;>>&#8221;, a saída será concatenada ao final do arquivo e o conteúdo (se houver) de &#8220;lista&#8221; será preservado. Para melhor entender isso, experimente executar a seguinte seqüência de comandos:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #000000; font-weight: bold;">&gt;&gt;</span> listagem
<span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #000000; font-weight: bold;">&gt;&gt;</span> listagem
<span style="color: #c20cb9; font-weight: bold;">less</span> listagem</pre></div></div>

<p>O redirecionamento neste exemplo, diferentemente do exemplo anterior, é denominado redirecionamento não-destrutivo.</p>
<h3><a name="pipe">4.2. Usando Pipelines</a></h3>
<p>Nos exemplos para o filtro sort, os dados de entrada eram digitados pelo usuário ou estavam gravados em um arquivo. O que aconteceria se quiséssemos ordenar dados vindos do saída de outro comando ? Para listar os arquivos do diretório corrente em ordem alfabética invertida devemos fazer com que a saída do comando ls seja ordenada pelo comando sort. Usando a opção &#8220;-r&#8221;, este comando ordena os dados na ordem inversa.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">ls</span>
historia  notas     tese      testes 
$ <span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #000000; font-weight: bold;">&gt;</span> lista 
$ <span style="color: #c20cb9; font-weight: bold;">sort</span> <span style="color: #660033;">-r</span> lista 
testes
tese
notas
lista                             <span style="color: #666666; font-style: italic;"># observe esse nome de arquivo</span>
historia</pre></div></div>

<p>Aqui, salvamos a saída do comando ls em um arquivo (lista) e usamos sort com a opção &#8220;-r&#8221;. Porém, isso faz com que tenhamos um arquivo temporário para armazenar os dados. Assim, toda vez que fizermos isso, teremos que, em seguida, remover o arquivo lista. A solução é usar o que chamamos de pipeline, outro recurso do shell que nos permite conectar vários comandos usando um pipe, onde a saída do primeiro comando é enviada diretamente à entrada do segundo e assim por diante no caso de haver mais de dois comandos conectados por pipes.</p>
<p>No nosso caso, queremos enviar a saída do comando ls para a entrada do comando sort. O símbolo &#8220;|&#8221; (barra vertical) é usado para criar um pipe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">sort</span> <span style="color: #660033;">-r</span> 
testes
tese
notas
historia</pre></div></div>

<p>Note que neste exemplo, nenhum nome de arquivo é usado na linha de comando, diferentemente do exemplo anterior que fazia o uso do arquivo intermediário lista. Outra diferença é que o nome desse arquivo intermediário aparece no resultado do penúltimo exemplo, mas não neste último. O comando é mais curto, mais fácil de digitar e o resultado é mais adequado pois não inclui nomes de arquivos intermediários.</p>
<p>É importante observar que o redirecionamento e o uso de pipes são características do shell e não dos comandos em si. É o shell quem provê a sintaxe dos símbolos &#8220;>&#8221;, &#8220;<" e "|". Logo, se você criar um programa que utilize entrada de dados via stdin, poderá usar redirecionamento para especificar uma entrada para o seu programa.</p>
<h3><a name="expansoes">5. Expansões</a></h3>
<p>Expansões são caracteres, ou uma sequência deles, que expressa outro significado. O intuito disso é facilitar e padronizar comandos.</p>
<p>~: path à home do usuário corrente<br />
~user: path à home do usuário &#8220;user&#8221;<br />
{a,b,c}: presença do caractere &#8220;a&#8221;, &#8220;b&#8221; ou &#8220;c&#8221;. Podem ser usadas strings em vez de simplesmente caracteres.</p>
<p>Exemplos:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> ~</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> ~root</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>std<span style="color: #7a0874; font-weight: bold;">&#123;</span><span style="color: #000000; font-weight: bold;">in</span>,out,err<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

<h4><a name="varexp">5.1. Expansão de Variáveis</a></h4>
<table width="100%">
<thead>
<tr>
<td>Sintaxe</td>
<td>Expansão</td>
</tr>
</thead>
<tbody>
<tr>
<td>${var:-texto}</td>
<td>Se var não está definida, retorna &#8216;texto&#8217;</td>
</tr>
<tr>
<td>${var:=texto}</td>
<td>Se var não está definida, defina-a com &#8216;texto&#8217;</td>
</tr>
<tr>
<td>${var:?texto}</td>
<td>Se var não está definida, retorna o erro &#8216;texto&#8217;</td>
</tr>
<tr>
<td>${var:+texto}</td>
<td>Se var está definida, retorna &#8216;texto&#8217;, senão retorna o vazio</td>
</tr>
<tr>
<td>${var}</td>
<td>É o mesmo que $var, porém não ambíguo</td>
</tr>
<tr>
<td>${#var}</td>
<td>Retorna o tamanho da string</td>
</tr>
<tr>
<td>${!var}</td>
<td>Executa o conteúdo de $var (igual &#8216;eval \$$var&#8217;)</td>
</tr>
<tr>
<td>${!texto*}</td>
<td>Retorna os nomes de variáveis começadas por &#8216;texto&#8217;</td>
</tr>
<tr>
<td>${var:N}</td>
<td>Retorna o texto a partir da posição &#8216;N&#8217;</td>
</tr>
<tr>
<td>${var:N:tam}</td>
<td>Retorna &#8216;tam&#8217; caracteres a partir da posição &#8216;N&#8217;</td>
</tr>
<tr>
<td>${var#texto}</td>
<td>Corta &#8216;texto&#8217; do início da string</td>
</tr>
<tr>
<td>${var##texto}</td>
<td>Corta &#8216;texto&#8217; do início da string (* guloso)</td>
</tr>
<tr>
<td>${var%texto}</td>
<td>Corta &#8216;texto&#8217; do final da string</td>
</tr>
<tr>
<td>${var%%texto}</td>
<td>Corta &#8216;texto&#8217; do final da string (* guloso)</td>
</tr>
<tr>
<td>${var/texto/novo}</td>
<td>Substitui &#8216;texto&#8217; por &#8216;novo&#8217;, uma vez</td>
</tr>
<tr>
<td>${var//texto/novo}</td>
<td>Substitui &#8216;texto&#8217; por &#8216;novo&#8217;, sempre</td>
</tr>
<tr>
<td>${var/#texto/novo}</td>
<td>Se a string começar com &#8216;texto&#8217;, substitui &#8216;texto&#8217; por &#8216;novo&#8217;</td>
</tr>
<tr>
<td>${var/%texto/novo}</td>
<td>Se a string terminar com &#8216;texto&#8217;, substitui &#8216;texto&#8217; por &#8216;novo&#8217;</td>
</tr>
</tbody>
</table>
<h3><a name="params">6. Parâmetros de linha de comando</a></h3>
<p>Assim como em outras linguagens, é possível passar parâmetros para scripts shell. Para isso, usam-se as variáveis $1, $2, &#8230; A variável $0 contém o comando chamado via linha de comando.</p>
<p>Exemplo:</p>
<p>Crie um arquivo &#8220;test.sh&#8221; com este conteúdo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'$0 = '</span><span style="color: #007800;">$0</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'$1 = '</span><span style="color: #007800;">$1</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'$2 = '</span><span style="color: #007800;">$2</span></pre></div></div>

<p>Veja as saídas das execuções abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ .<span style="color: #000000; font-weight: bold;">/</span>test.sh 
<span style="color: #007800;">$0</span> = .<span style="color: #000000; font-weight: bold;">/</span>test.sh
<span style="color: #007800;">$1</span> = 
<span style="color: #007800;">$2</span> = 
$ .<span style="color: #000000; font-weight: bold;">/</span>test.sh um
<span style="color: #007800;">$0</span> = .<span style="color: #000000; font-weight: bold;">/</span>test.sh
<span style="color: #007800;">$1</span> = um
<span style="color: #007800;">$2</span> = 
$ .<span style="color: #000000; font-weight: bold;">/</span>test.sh um dois
<span style="color: #007800;">$0</span> = .<span style="color: #000000; font-weight: bold;">/</span>test.sh
<span style="color: #007800;">$1</span> = um
<span style="color: #007800;">$2</span> = dois</pre></div></div>

<h3><a name="funcs">7. Definindo Funções</a></h3>
<p>Sintaxe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> nome_da_funcao<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#123;</span>
     <span style="color: #000000; font-weight: bold;">&lt;</span>comandos<span style="color: #000000; font-weight: bold;">&gt;</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

<p>Para chamar a função:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">nome_da_funcao
&nbsp;
<span style="color: #666666; font-style: italic;"># caso haja parâmetros</span>
nome_da_funcao param1 param2 ...</pre></div></div>

<p>Exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> imprime<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#123;</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Sou a função '<span style="color: #007800;">${0}</span>'&quot;</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Param 1: <span style="color: #007800;">${1}</span>&quot;</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Param 2: <span style="color: #007800;">${2}</span>&quot;</span>
	<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Lista de parâmetros: <span style="color: #007800;">${*}</span>&quot;</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
imprime um dois tres quatro</pre></div></div>

<p>Da mesma forma como foram usados $0, $1 etc anteriormente, aqui essas variáveis são usadas para retornar os parâmetros da função. Logo, percebe-se que, dentro de funções, não é possível acessar parâmetros de script, a menos que eles sejam passados por parâmetro para a função.</p>
<h4><a name="return">7.1. Retorno de Funções</a></h4>
<p>Antes de tudo, é preciso diferenciar retorno de função e saída de função. Por exemplo, ao se executar o comando &#8220;cat /etc/passwd&#8221;, a saída é o conteúdo do arquivo; o retorno é 0 (ou outro valor, caso ocorra erro). O retorno de uma função shell é um valor inteiro, normalmente utilizado para definir o status da função, ou seja, se ocorreu algum erro ou e ela foi executada corretamente.</p>
<p>Para obter o valor de retorno de uma função, usa-se a variável &#8220;$?&#8221;. Ela exibe o retorno do último  comando executado. Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">passwd</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$?</span></pre></div></div>

<p>Para retornar valor (status) numa função, usa-se o comando return.</p>
<p>Exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/bash</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> retorna<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#123;</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;sou um valor&quot;</span>
    <span style="color: #7a0874; font-weight: bold;">return</span> <span style="color: #000000;">42</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #007800;">valor</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span>retorna<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$?</span>
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$valor</span></pre></div></div>

<p>Ao se executar a função, sua saída será &#8220;sou um valor&#8221;; seu retorno será 42.</p>
<p>Em shell, considera-se o valor 0 como execução bem sucedida. Qualquer outro valor representa erro. É por isso que recomenda-se que toda função <code>main</code> de um programa em C retorne o valor 0, desde que não ocorra algum erro.</p>
<h3><a name="er">8. Expressões Regulares em Bash</a></h3>
<p>Expressões regulares em shell podem ser usadas em comparações (if&#8217;s), por exemplo. Em if&#8217;s, usa-se o operador &#8220;=~&#8221; para realizar comparações usando ER&#8217;s:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #007800;">s</span>=<span style="color: #ff0000;">&quot;bash&quot;</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$s</span>&quot;</span> =~ ^b <span style="color: #7a0874; font-weight: bold;">&#93;</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #000000; font-weight: bold;">then</span>
    <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">'começa com b'</span>
<span style="color: #000000; font-weight: bold;">fi</span></pre></div></div>

<h3><a name="mathexp">9. Expressões Matemáticas</a></h3>
<p>O bash não trabalha com expressões matemáticas tão facilmente. Existe o comando &#8220;let&#8221;, que permite realizar expressões matemáticas, mas é mais comum se usar a sintaxe semelhante ao C, utilizando dois parênteses:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #007800;">a</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000;">1</span> + <span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
$ <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>i++<span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
$ <span style="color: #007800;">x</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span>x<span style="color: #000000; font-weight: bold;">*</span><span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
...</pre></div></div>

<h3><a name="bashrc">10. O Arquivo .bashrc</a></h3>
<p>Na home dos usuários (~), é comum haver o arquivo .bashrc (o ponto no início indica que o arquivo é oculto). Esse arquivo é sempre executado quando se abre um shell. Nele, constam diversas configurações, como definição de variáveis de ambientes, definição de aliases etc. Você pode editar esse arquivo (ou criá-lo, caso não exista):</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #c20cb9; font-weight: bold;">vim</span> ~<span style="color: #000000; font-weight: bold;">/</span>.bashrc</pre></div></div>

<p>É possível usar outros editores, não apenas o vim.</p>
<h3><a name="alias">11. Aliases (Apelidos)</a></h3>
<p>Algumas vezes usamos comandos que necessitam de várias opções e argumentos. Para amenizar o trabalho de digitarmos repetidamente estes comandos o bash oferece um recurso chamado alias com o qual podemos definir sinônimos ou &#8220;apelidos&#8221; para um comando. Um alias pode ser definido na linha de comando da seguinte forma:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #000000; font-weight: bold;">&lt;</span>nome<span style="color: #000000; font-weight: bold;">&gt;</span>=<span style="color: #000000; font-weight: bold;">&lt;</span>comando<span style="color: #000000; font-weight: bold;">&gt;</span></pre></div></div>

<p>Observe que não pode haver espaços em branco antes ou depois do &#8220;=&#8221;.</p>
<p>Esta sintaxe indica que nome é um &#8220;alias&#8221; (apelido) para comando. Toda vez que digitarmos o comando &#8220;nome&#8221;, o bash o substituirá por &#8220;comando&#8221;.</p>
<p>Exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #7a0874; font-weight: bold;">alias</span> <span style="color: #007800;">lf</span>=<span style="color: #ff0000;">'ls -F'</span></pre></div></div>

<p>Isso fará o shell executar &#8220;ls -F&#8221; toda vez que usarmos &#8220;lf&#8221; na linha de comando. Ou seja, o que o alias faz na verdade é substituir a palavra &#8220;lf&#8221; por &#8220;ls -F&#8221;. Observe neste exemplo, existe um espaço em branco entre ls e -F. Sempre que houver espaços em branco na definição de um campo, todo o campo deve ser digitado entre aspas simples (&#8216;) ou duplas (&#8220;).</p>
<p>É possível definir aliases em seu .bashrc, para que eles estejam sempre disponíveis na sua sessão.</p>
<h3><a name="refs">12. Referências</a></h3>
<p>Linux Básico:<br />
http://www.inf.ufpr.br/nicolui/Docs/Livros/LinuxBasico/ ou http://www.inf.ufpr.br/nicolui/Docs/Livros/LinuxBasico.pdf</p>
<p>Linux Avançado</p>
<p>http://www.inf.ufpr.br/nicolui/Docs/Livros/LinuxAvancado.pdf</p>
<p>Canivete Suiço do Shell (Bash)</p>
<p>http://aurelio.net/shell/canivete/</p>
<p>Livro Shell Script Profissional (Livro físico):</p>
<p>http://www.shellscript.com.br/</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/curso-de-shell-script-modulo-1-scripts-shell-estruturas/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Servidor WEB Simples em Python</title>
		<link>http://www.rberaldo.com.br/blog/servidor-web-simples-em-python/</link>
		<comments>http://www.rberaldo.com.br/blog/servidor-web-simples-em-python/#comments</comments>
		<pubDate>Sat, 30 Apr 2011 17:56:19 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Programação]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[monothread]]></category>
		<category><![CDATA[multithread]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[servidor]]></category>
		<category><![CDATA[simples]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=445</guid>
		<description><![CDATA[Algumas vezes pode ser necessário implementar um servidor WEB simples, para uso pessoal, em pequenas aplicações ou em máquinas com poucos recursos. Em situações assim, Apache ou Tomcat são exageradamente pesados e desnecessários. O Python possui bibliotecas para implementação de servidores WEB simples. Há versão de apenas uma thread (atende uma requisição por vez) ou [...]]]></description>
			<content:encoded><![CDATA[<p>Algumas vezes pode ser necessário implementar um servidor WEB simples, para uso pessoal, em pequenas aplicações ou em máquinas com poucos recursos. Em situações assim, Apache ou Tomcat são exageradamente pesados e desnecessários.</p>
<p>O Python possui bibliotecas para implementação de servidores WEB simples. Há versão de apenas uma thread (atende uma requisição por vez) ou multi-thread (atende diversas requisições simultaneamente).</p>
<p><span id="more-445"></span></p>
<p>Os exemplos abaixo apenas enviam al cliente uma mensagem &#8220;INICIO&#8221;, esperam 2 segundos, e enviam outra mensagem, &#8220;FIM&#8221;. A espera por 2 segundos será útil apenas para enfatizar a diferença entre as versões monothread e multi-thread.</p>
<p>Os códigos funcionam em qualquer Sistema Operacional com Python instalado, mas os exemplos de execução que mostrarei são voltados para Linux ou Mac OS, onde há um terminal com suporte a bash e curl. Porém, nada impede que os testes sejam feitos em navegadores.</p>
<p>Versão simples, com apenas uma thread, ou seja, atende apenas uma requisição por vez:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/env python</span>
<span style="color: #808080; font-style: italic;"># coding: utf-8</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">BaseHTTPServer</span> <span style="color: #ff7700;font-weight:bold;">import</span> BaseHTTPRequestHandler
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">urlparse</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Porta onde o servidor rodará</span>
PORT = <span style="color: #ff4500;">8888</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> GetHandler<span style="color: black;">&#40;</span>BaseHTTPRequestHandler<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> do_GET<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">send_response</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">200</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">end_headers</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">wfile</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span> <span style="color: #483d8b;">&quot;INICIO<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: black;">&#41;</span>
        <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span> <span style="color: #ff4500;">2</span> <span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">wfile</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span> <span style="color: #483d8b;">&quot;FIM<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    <span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">BaseHTTPServer</span> <span style="color: #ff7700;font-weight:bold;">import</span> HTTPServer
    server = HTTPServer<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'localhost'</span>, PORT<span style="color: black;">&#41;</span>, GetHandler<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Starting server, use &lt;Ctrl-C&gt; to stop'</span>
    server.<span style="color: black;">serve_forever</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>Para executar:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ python monothread.py</pre></div></div>

<p>Ou, caso você dê permissão de execução ao script:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ .<span style="color: #000000; font-weight: bold;">/</span>monothread.py</pre></div></div>

<p>Para enviar solicitações ao servidor, sugiro este comando:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span> i = <span style="color: #000000;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> <span style="color: #000000;">5</span>; i++ <span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> ; <span style="color: #000000; font-weight: bold;">do</span> curl http:<span style="color: #000000; font-weight: bold;">//</span>localhost:<span style="color: #000000;">8888</span> <span style="color: #000000; font-weight: bold;">&amp;</span> <span style="color: #000000; font-weight: bold;">done</span>;</pre></div></div>

<p>Você verá que cada requisição será atendida de cada vez. Ou seja, ao terminar a requisição 1, inicia-se o atendimento à requisição 2, mesmo que todas as 5 requisições tenham sido feitas &#8220;ao mesmo tempo&#8221; (note o &#038; indicando que o cURL rodará em background).<br />
Você verá que cada par &#8220;INICIO&#8221; e &#8220;FIM&#8221; aparecerão sequencialmente, mostrando que cada requisição é atendida individualmente.</p>
<p>Versão multi-thread, ou seja, atende várias requisições simultaneamente:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
</pre></td><td class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/env python</span>
<span style="color: #808080; font-style: italic;"># coding: utf-8</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">BaseHTTPServer</span> <span style="color: #ff7700;font-weight:bold;">import</span> HTTPServer, BaseHTTPRequestHandler
<span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">SocketServer</span> <span style="color: #ff7700;font-weight:bold;">import</span> ThreadingMixIn
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">threading</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Porta onde o servidor rodará</span>
PORT = <span style="color: #ff4500;">8888</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Handler<span style="color: black;">&#40;</span>BaseHTTPRequestHandler<span style="color: black;">&#41;</span>:
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> do_GET<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
&nbsp;
        <span style="color: #008000;">self</span>.<span style="color: black;">send_response</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">200</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">end_headers</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">wfile</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'INICIO<span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: black;">&#41;</span>
        <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span> <span style="color: #ff4500;">2</span> <span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">wfile</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'FIM!<span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> ThreadedHTTPServer<span style="color: black;">&#40;</span>ThreadingMixIn, HTTPServer<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;&quot;Handle requests in a separate thread.&quot;&quot;&quot;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    server = ThreadedHTTPServer<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'localhost'</span>, PORT<span style="color: black;">&#41;</span>, Handler<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Starting server, use &lt;Ctrl-C&gt; to stop'</span>
    server.<span style="color: black;">serve_forever</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></td></tr></table></div>

<p>O procedimento para execução é o mesmo do anterior. Para testar, vamos usar o mesmo loop de requisições:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #7a0874; font-weight: bold;">&#40;</span> i = <span style="color: #000000;">0</span>; i <span style="color: #000000; font-weight: bold;">&lt;</span> <span style="color: #000000;">5</span>; i++ <span style="color: #7a0874; font-weight: bold;">&#41;</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> ; <span style="color: #000000; font-weight: bold;">do</span> curl http:<span style="color: #000000; font-weight: bold;">//</span>localhost:<span style="color: #000000;">8888</span> <span style="color: #000000; font-weight: bold;">&amp;</span> <span style="color: #000000; font-weight: bold;">done</span>;</pre></div></div>

<p>Dessa vez, todas as requisições serão atendidas ao mesmo tempo. A palavra &#8220;INICIO&#8221; aparecerá 5 vezes de uma só vez, e os logs de requisição do servidor aparecerão os 5 de uma só vez.</p>
<p>Os códigos acima foram adaptados deste link:<br />
<a href="http://blog.doughellmann.com/2007/12/pymotw-basehttpserver.html" target="_blank" onclick="urchinTracker('/outgoing/blog.doughellmann.com/2007/12/pymotw-basehttpserver.html?referer=');">http://blog.doughellmann.com/2007/12/pymotw-basehttpserver.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/servidor-web-simples-em-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A extensão MySQLi do PHP</title>
		<link>http://www.rberaldo.com.br/blog/a-extensao-mysqli-do-php/</link>
		<comments>http://www.rberaldo.com.br/blog/a-extensao-mysqli-do-php/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 13:57:02 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Banco de Dados]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[banco]]></category>
		<category><![CDATA[base]]></category>
		<category><![CDATA[dados]]></category>
		<category><![CDATA[mysqli]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=431</guid>
		<description><![CDATA[O PHP possui a extensão MySQL nativamente desde o PHP 4. No PHP 5 foi adicionada a extensão MySQLi, que é uma versão mais completa e recente da antiga extensão MySQL. Além disso, a extensão MySQLi é totalmente orientada e objetos. Essa nova extensão também viabiliza o uso de novos recursos do MySQL, como Stored [...]]]></description>
			<content:encoded><![CDATA[<p>O PHP possui a extensão MySQL nativamente desde o PHP 4. No PHP 5 foi adicionada a extensão MySQLi, que é uma versão mais completa e recente da antiga extensão MySQL. Além disso, a extensão MySQLi é totalmente orientada e objetos. Essa nova extensão também viabiliza o uso de novos recursos do MySQL, como Stored Procedures ou Views.</p>
<p>A extensão MySQLi necessita do servidor MySQL 4.1 ou superior.</p>
<p>Vale lembrar que há boatos de que a extensão MySQL deixe de existir no PHP 6. Logo, seja isso verdade ou não, é preferível usar MySQLi.</p>
<p>Vou mostrar aqui a forma de se trabalhar com a extensão MySQLi.</p>
<p><span id="more-431"></span></p>
<p>Para realizar a conexão com a base de dados, basta isto:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$MySQLi</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> mysqli<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'servidor'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'usuario'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'senha'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'nome_da_db'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Por exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$MySQLi</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> mysqli<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'localhost'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'root'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'passwd'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'test'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Se a conexão for bem sucedida, $MySQLi será um objeto, que será usado para consultas posteriores e outras ações com a base de dados.</p>
<p>Para realizar uma consulta, por exemplo, basta usar o método query() e percorrer com fetch_assoc(), muito semelhante ao que se faz usando a extensão mysql:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$exec</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$MySQLi</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">query</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'select dados from tabela'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$f</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$exec</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">fetch_assoc</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #990000;">print_r</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$f</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A lista completa de propriedades e métodos da classe MySQLi pode ser encontrada no link abaixo:</p>
<p><a href="http://php.net/manual/pt_BR/book.mysqli.php" target="_blank" onclick="urchinTracker('/outgoing/php.net/manual/pt_BR/book.mysqli.php?referer=');">http://php.net/manual/pt_BR/book.mysqli.php</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/a-extensao-mysqli-do-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>C: Por que usar fgets em vez de gets</title>
		<link>http://www.rberaldo.com.br/blog/c-por-que-usar-fgets-em-vez-de-gets/</link>
		<comments>http://www.rberaldo.com.br/blog/c-por-que-usar-fgets-em-vez-de-gets/#comments</comments>
		<pubDate>Sun, 23 Jan 2011 14:51:32 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[C/C++]]></category>
		<category><![CDATA[Dicas]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Segurança]]></category>
		<category><![CDATA[buffer]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[fgets]]></category>
		<category><![CDATA[gets]]></category>
		<category><![CDATA[limite]]></category>
		<category><![CDATA[segurança]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=316</guid>
		<description><![CDATA[Exemplo de como gets pode gerar erros em programas escritos em C. Solução: usar fgets]]></description>
			<content:encoded><![CDATA[<p>A função gets, da biblioteca padrão do C (<em>stdio</em>) pode gerar um grande problema para o programador que a usa: como essa função não limita o número de caracteres a serem lidos da entrada padrão (<em>stdin</em>), pode haver vazamento de memória, ou até pior, injeção de código malicioso no progreama.</p>
<p>A solução é usar fgets, que limita o <em>buffer</em> de leitura.</p>
<p><span id="more-316"></span></p>
<p>Como a própria <a href="http://en.wikipedia.org/wiki/Man_page" title="Link para o artigo sobre Man Page na Wikiéida" onclick="urchinTracker('/outgoing/en.wikipedia.org/wiki/Man_page?referer=');"><em>manpage</em></a> da função gets informa, é preferível o uso de fgets. Leia o trecho presente na <a href="http://www.linuxmanpages.com/man3/gets.3.php" title="Link para a manpage de gets" onclick="urchinTracker('/outgoing/www.linuxmanpages.com/man3/gets.3.php?referer=');"><strong><em>manpage</em> de gets</strong></a>:</p>
<pre>
BUGS

Never use gets(). Because it is impossible to tell without knowing the data
in advance how many characters gets() will read, and because gets() will
continue to store characters past the end of the buffer, it is extremely
dangerous to use. It has been used to break computer security. Use fgets()
instead.
</pre>
<p>Vejamos um simples exemplo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define STRSIZE 10</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">char</span> str<span style="color: #009900;">&#91;</span> STRSIZE <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	gets<span style="color: #009900;">&#40;</span> str <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span> <span style="color: #ff0000;">&quot;%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> str <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>A própria compilação com o GCC já alerta sobre o problema de gets:</p>
<pre style="overflow: auto;">
$ gcc teste.c
/tmp/ccCUw08x.o: In function `main':
teste.c:(.text+0x1f): warning: the `gets' function is dangerous and should not be used.
</pre>
<p>Dependendo da posição da memória em que o programa for executado, pode ocorrer o seguinte problema durante sua execução:</p>
<pre style="overflow: auto;">
$ ./a.out
oi eu sou o beraldo
oi eu sou o beraldo
*** stack smashing detected ***: ./a.out terminated
======= Backtrace: =========
/lib/libc.so.6(__fortify_fail+0x37)[0x7f8b96f57537]
/lib/libc.so.6(__fortify_fail+0x0)[0x7f8b96f57500]
./a.out[0x4005fc]
/lib/libc.so.6(__libc_start_main+0xfe)[0x7f8b96e76d8e]
./a.out[0x4004f9]
======= Memory map: ========
00400000-00401000 r-xp 00000000 08:03 403972                             /tmp/a.out
00600000-00601000 r--p 00000000 08:03 403972                             /tmp/a.out
00601000-00602000 rw-p 00001000 08:03 403972                             /tmp/a.out
00ca3000-00cc4000 rw-p 00000000 00:00 0                                  [heap]
7f8b96c42000-7f8b96c57000 r-xp 00000000 08:03 524368                     /lib/libgcc_s.so.1
7f8b96c57000-7f8b96e56000 ---p 00015000 08:03 524368                     /lib/libgcc_s.so.1
7f8b96e56000-7f8b96e57000 r--p 00014000 08:03 524368                     /lib/libgcc_s.so.1
7f8b96e57000-7f8b96e58000 rw-p 00015000 08:03 524368                     /lib/libgcc_s.so.1
7f8b96e58000-7f8b96fd2000 r-xp 00000000 08:03 546662                     /lib/libc-2.12.1.so
7f8b96fd2000-7f8b971d1000 ---p 0017a000 08:03 546662                     /lib/libc-2.12.1.so
7f8b971d1000-7f8b971d5000 r--p 00179000 08:03 546662                     /lib/libc-2.12.1.so
7f8b971d5000-7f8b971d6000 rw-p 0017d000 08:03 546662                     /lib/libc-2.12.1.so
7f8b971d6000-7f8b971db000 rw-p 00000000 00:00 0
7f8b971db000-7f8b971fb000 r-xp 00000000 08:03 526899                     /lib/ld-2.12.1.so
7f8b973d4000-7f8b973d7000 rw-p 00000000 00:00 0
7f8b973f7000-7f8b973fb000 rw-p 00000000 00:00 0
7f8b973fb000-7f8b973fc000 r--p 00020000 08:03 526899                     /lib/ld-2.12.1.so
7f8b973fc000-7f8b973fd000 rw-p 00021000 08:03 526899                     /lib/ld-2.12.1.so
7f8b973fd000-7f8b973fe000 rw-p 00000000 00:00 0
7fff0445e000-7fff0447f000 rw-p 00000000 00:00 0                          [stack]
7fff0454c000-7fff0454d000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Abortado
</pre>
<p>Isso nem sempre ocorre. Depende dos limites de memória alocados para a execução do programa.</p>
<p>Teoricamente, na string só deveria conter &#8220;oi eu sou &#8220;, que são os dez primeiros caracteres da string lida. Assim, os demais caracteres ficam além dessa última posição de memória, que pode estar em uso por outra aplicação, gerando o erro. Pior que isso, se for injetado um código malicioso, a outra aplicação poderá executá-lo. Essa é uma forma de &#8220;vírus&#8221;.</p>
<p>A solução é usar fgets, lendo de <em>stdin</em>, que é o arquivo que representa a entrada padrão:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="c" style="font-family:monospace;"><span style="color: #339933;">#include &lt;stdio.h&gt;</span>
&nbsp;
<span style="color: #339933;">#define STRSIZE 10</span>
&nbsp;
<span style="color: #993333;">int</span> main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #993333;">char</span> str<span style="color: #009900;">&#91;</span> STRSIZE <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	fgets<span style="color: #009900;">&#40;</span> str<span style="color: #339933;">,</span> STRSIZE<span style="color: #339933;">,</span> stdin <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000066;">printf</span><span style="color: #009900;">&#40;</span> <span style="color: #ff0000;">&quot;%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> str <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Compilação e execução:</p>
<pre>
$ gcc teste.c
$ ./a.out
oi eu sou o beraldo
oi eu sou
</pre>
<p>O resultado foi o esperado.</p>
<p>Portanto, excluam gets de suas vidas. =)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/c-por-que-usar-fgets-em-vez-de-gets/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Segurança em Sistemas de Login: Proteção Contra SQL Injection</title>
		<link>http://www.rberaldo.com.br/blog/seguranca-em-sistemas-de-login-protecao-contra-sql-injection/</link>
		<comments>http://www.rberaldo.com.br/blog/seguranca-em-sistemas-de-login-protecao-contra-sql-injection/#comments</comments>
		<pubDate>Mon, 27 Dec 2010 15:45:48 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Banco de Dados]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Segurança]]></category>
		<category><![CDATA[escape]]></category>
		<category><![CDATA[injection]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[magic]]></category>
		<category><![CDATA[magic_quotes]]></category>
		<category><![CDATA[mysql_real_escape_string]]></category>
		<category><![CDATA[pg_escape_string]]></category>
		<category><![CDATA[quotes]]></category>
		<category><![CDATA[segurança]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[stripslashes]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=269</guid>
		<description><![CDATA[Dando continuação ao artigo sobre Segurança em Sistemas de login, hoje mostrarei como se defender de ataques por SQL Injection. Foco MySQL e PostgreSQL, os principais SGBDs gratuitos da atualidade.]]></description>
			<content:encoded><![CDATA[<p>Dando continuação ao artigo sobre Segurança em Sistemas de login, hoje mostrarei como se defender de ataques por SQL Injection. Foco MySQL e PostgreSQL, os principais SGBDs gratuitos da atualidade.</p>
<p>Caso não tenha visto a primeira parte do artigo, leia-a aqui:<br />
<a href="http://www.rberaldo.com.br/blog/2010/12/22/seguranca-em-sistemas-de-login-senhas-e-cookies/">Segurança em SIstemas de Login: Senhas e Cookies</a></p>
<p><span id="more-269"></span></p>
<h3>Sumário</h3>
<p><a href="#intro">1. Introdução</a><br />
<a href="#magic">2. Magic Quotes</a><br />
<a href="#solucoes">3. Soluções Especificas para cada SGBD</a><br />
<a href="#mysql">3.1. MySQL</a><br />
<a href="#postgre">3.2. PostgreSQL</a><br />
<a href="#exemplos">3.3. Exemplos de códigos para MySQL e PostgreSQL</a><br />
<a href="#apenas">4. Apenas Isso Não Basta</a><br />
<a href="#conclusao">5. Conclusão</a></p>
<h3><a name="intro">1. Introdução</a></h3>
<p>Neste segundo artigo sobre <b>segurança</b> em sistemas de login, abordarei formas de proteção contra <a href="http://pt.wikipedia.org/wiki/Inje%C3%A7%C3%A3o_de_SQL" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/Inje_C3_A7_C3_A3o_de_SQL?referer=');">SQL Injection</a>.</p>
<p>Existem muitas discussões na Internet, em listas de discussão e fóruns, sobre qual seria a função perfeita para impedir ataque por SQL Injection SQL Injection. Alguns programadores até criam funções que removem, por segurança, palavras-chave da linguagem SQL, como SELECT, DROP, DELETE. Isso pode até resolver, mas não podemos danificar a informação; se permitirmos que o usuário escreva informações em nosso site, devemos permitir-lhe escrever<br />
SELECT, DROP e DELETE também. Imagine, por exemplo, um fórum sobre programação: como poderíamos postar códigos SQL se o fórum removesse as palavras SELECT, DELETE etc? Logo, não podemos remover essas palavras.</p>
<p>A soluçãoo é muito simples! Sim, é simples, mesmo. Muitos querem complicar à toa, porém é muito simples: <strong>escapar caracteres especiais</strong>.</p>
<p>Esses caracteres especiais podem variar conforme o <a href="http://pt.wikipedia.org/wiki/Sistema_de_gerenciamento_de_banco_de_dados" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/Sistema_de_gerenciamento_de_banco_de_dados?referer=');">SGBD</a> que se está utilizando. Normalmente são aspas simples e duplas, as quais delimitam strings em um comando SQL.</p>
<p>Vamos a um exemplo. Considere a SQL abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">$sql <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;SELECT id, nome, sobrenome FROM autores WHERE nome = '&quot;</span> <span style="color: #66cc66;">.</span> $nome <span style="color: #66cc66;">.</span> <span style="color: #ff0000;">&quot;'
		AND sobrenome = '&quot;</span> <span style="color: #66cc66;">.</span> $sobrenome <span style="color: #66cc66;">.</span> <span style="color: #ff0000;">&quot;'&quot;</span>;</pre></div></div>

<p>Supondo que $nome contenha <b>jo&#8217;sé</b>, e $sobrenome, <b>silva</b>, a SQL ficará assim:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> id<span style="color: #66cc66;">,</span> nome<span style="color: #66cc66;">,</span> sobrenome <span style="color: #993333; font-weight: bold;">FROM</span> autores <span style="color: #993333; font-weight: bold;">WHERE</span> nome <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'jo'</span>se<span style="color: #ff0000;">' AND sobrenome = '</span>silva<span style="color: #ff0000;">';</span></pre></div></div>

<p>Isso gera um erro de sintaxe, sem comprometer o banco de dados. Porém, se mantivermos $sobrenome e definirmos $nome com o valor <b>jo&#8217;; DROP TABLE autores ; &#8211;</b>, teremos:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> id<span style="color: #66cc66;">,</span> nome<span style="color: #66cc66;">,</span> sobrenome <span style="color: #993333; font-weight: bold;">FROM</span> autores <span style="color: #993333; font-weight: bold;">WHERE</span> nome <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">'jo'</span>; <span style="color: #993333; font-weight: bold;">DROP</span> <span style="color: #993333; font-weight: bold;">TABLE</span> autores ;
<span style="color: #808080; font-style: italic;">--'AND sobrenome = 'silva';</span></pre></div></div>

<p>Dessa forma, selecionam-se os registros com nome igual a &#8220;jo&#8221;, remove-se a tabela &#8220;autores&#8221; e considera-se <strong>&#8216; AND sobrenome = &#8216;silva&#8217;;</strong> como comentário. Isso caracteriza um ataque por SQL Injection.</p>
<h3><a name="magic">2. Magic Quotes</a></h3>
<p>Face aos possíveis grandes danos que SQL Injection pode causar, o PHP possui um mecanismo nativo automático para escapar caracteres especiais: o <em>magic quotes</em>. Porém, esse é um mecanismo genérico, que não pode ser aplicado a todos os SGBDs. Logo, não o utilize!</p>
<p>O próprio Manual do PHP não recomenda seu uso:</p>

<div class="wp_syntax"><div class="code"><pre class="plain" style="font-family:monospace;">There is no reason to use magic quotes because they are no longer a supported
part of PHP. However, they did exist and did help a few beginners blissfully
and unknowingly write better (more secure) code. But, when dealing with code
that relies upon this behavior it's better to update the code instead of
turning magic quotes on. So why did this feature exist? Simple, to help prevent
SQL Injection. Today developers are better aware of security and end up using
database specific escaping mechanisms and/or prepared statements instead of
relying upon features like magical quotes.</pre></div></div>

<p>Fonte: <a href="http://br3.php.net/manual/en/security.magicquotes.why.php" onclick="urchinTracker('/outgoing/br3.php.net/manual/en/security.magicquotes.why.php?referer=');">http://br3.php.net/manual/en/security.magicquotes.why.php</a></p>
<p>Como citado no trecho, é preferível adaptar seus códigos a fim de torná-los seguros e não vulneráveis a SQL Injection a habilitar o magic quotes. Portanto mantenha a diretiva <strong>magic_quotes_gpc</strong>, do , em <strong>off</strong>! Dê preferência a funções específicas para cada SGBD.</p>
<p>Leia o capítulo sobre Magic Quotes, do }Manual do PHP, no link abaixo:<br />
<a href="http://br3.php.net/manual/en/security.magicquotes.php" onclick="urchinTracker('/outgoing/br3.php.net/manual/en/security.magicquotes.php?referer=');">http://br3.php.net/manual/en/security.magicquotes.php</a></p>
<h3><a name="solucoes">3. Soluções Especificas para cada SGBD</a></h3>
<h3><a name="mysql">3.1. MySQL</a></h3>
<p>Vamos ao exemplo mais comum: MySQL: existe uma função específica do PHP para escapar caracteres especiais do MySQL: <a href="http://br3.php.net/manual/pt\_BR/function.mysql-real-escape-string.php" onclick="urchinTracker('/outgoing/br3.php.net/manual/pt_BR/function.mysql-real-escape-string.php?referer=');">mysql_real_escape_string</a>.</p>
<p>Ela deve ser usada com magic_quotes_gpc em off. Caso seu servidor mantenha essa diretiva ativa, <a href="http://php.net/manual/pt_BR/security.magicquotes.disabling.php" onclick="urchinTracker('/outgoing/php.net/manual/pt_BR/security.magicquotes.disabling.php?referer=');">desabilite-a por meio de htaccess</a> ou, caso isso não seja possível, certifique-se de usar <a href="http://php.net/manual/en/function.stripslashes.php" onclick="urchinTracker('/outgoing/php.net/manual/en/function.stripslashes.php?referer=');">stripslashes</a> antes de aplicar essa função. Veja o exemplo abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #990000;">get_magic_quotes_gpc</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$name</span> <span style="color: #339933;">=</span> <span style="color: #990000;">stripslashes</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$name</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000088;">$name</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$name</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;SELECT * FROM users WHERE name=<span style="color: #006699; font-weight: bold;">$name</span>&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Esse trecho de código e outras dicas sobre prevenção de SQL Injection com MySQL podem ser vistas no link abaixo, do próprio Manual do MySQL:<br />
<a href="http://dev.mysql.com/tech-resources/articles/guide-to-php-security.html" onclick="urchinTracker('/outgoing/dev.mysql.com/tech-resources/articles/guide-to-php-security.html?referer=');">http://dev.mysql.com/tech-resources/articles/guide-to-php-security.html</a></p>
<h3><a name="postgre">3.2. PostgreSQL</a></h3>
<p>O escape de caracteres no PostgreSQL não é feito com barra invertida; é feito com aspas simples. Ou seja, addslashes não funcionaria aqui.</p>
<p>O PHP também tem uma função específica para escape de caracteres especiais para PostgreSQL: <a href="http://php.net/manual/en/function.pg-escape-string.php" onclick="urchinTracker('/outgoing/php.net/manual/en/function.pg-escape-string.php?referer=');">pg_escape_string</a>.</p>
<p>Mais informações sobre prevenção de SQL Injection em PostgreSQL podem ser vistas no link abaixo, do Wiki do PostgreSQL:<br />
<a href="http://wiki.postgresql.org/wiki/Sql_injection" onclick="urchinTracker('/outgoing/wiki.postgresql.org/wiki/Sql_injection?referer=');">http://wiki.postgresql.org/wiki/Sql_injection</a></p>
<h3><a name="exemplos">3.3. Exemplos de códigos para MySQL e PostgreSQL</a></h3>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">mysql_connect</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'localhost'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'usuario'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'senha'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;There's no place like 127.0.0.1, the <span style="color: #000099; font-weight: bold;">\&quot;</span>localhost<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;String:	&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$str</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;MySQL:	&quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Postgre:	&quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">pg_escape_string</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>* Para usar mysql\_real\_escape\_string, é necessário uma conexão MySQL ativa.\\</p>
<p>Saída:</p>

<div class="wp_syntax"><div class="code"><pre class="plain" style="font-family:monospace;">String:	There's no place like 127.0.0.1, the &quot;localhost&quot;
MySQL:	There\'s no place like 127.0.0.1, the \&quot;localhost\&quot;
Postgre:	There''s no place like 127.0.0.1, the &quot;localhost&quot;</pre></div></div>

<h3><a name="apenas">4. Apenas Isso Não Basta</a></h3>
<p>Apenas escapar caracteres não é suficiente, uma vez que não existem apenas strings. Também temos dados numéricos, como inteiros, floats e outros tipos de ponto flutuante, que não são envolvidos por aspas em consultas SQL.</p>
<p>Considere a seguinte SQL:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;">$sql <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;SELECT id, nome, sobrenome FROM autores WHERE id=&quot;</span> <span style="color: #66cc66;">.</span> $id;</pre></div></div>

<p>Se $id tiver o valor <strong>0; DROP TABLE autores; &#8211;</strong>, a SQL final será:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">SELECT id<span style="color: #339933;">,</span> nome<span style="color: #339933;">,</span> sobrenome FROM autores WHERE id<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> DROP TABLE autores<span style="color: #339933;">;</span> <span style="color: #339933;">--;</span></pre></div></div>

<p>Isso removeria a tabela &#8220;autores&#8221;.</p>
<p>A solução é, novamente, muito simples: basta fazer <a href="http://en.wikipedia.org/wiki/Cast_(computer_science)" onclick="urchinTracker('/outgoing/en.wikipedia.org/wiki/Cast_computer_science?referer=');"><em>casting</em></a>, ou coerção, convertendo o parâmetro para um tipo numérico.</p>
<p>No exemplo acima, bastaria isto:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$id</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>int<span style="color: #009900;">&#41;</span> <span style="color: #000088;">$id</span><span style="color: #339933;">;</span></pre></div></div>

<p>O mesmo vale para float, double e os demais tipos de dados.</p>
<h3><a name="conclusao">5. Conclusão</a></h3>
<p>SQL Injection é um problema muito grave, que muitos programadores iniciantes deixam passar despercebido, principalmente por falta de conhecimento.</p>
<p>Apesar disso, sua prevenção é muito simples. Basta entender o funcionamento do ataque para saber como se defender dele.</p>
<p>Abraços,</p>
<p>Beraldo</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/seguranca-em-sistemas-de-login-protecao-contra-sql-injection/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Segurança em sistemas de login: senhas e cookies</title>
		<link>http://www.rberaldo.com.br/blog/seguranca-em-sistemas-de-login-senhas-e-cookies/</link>
		<comments>http://www.rberaldo.com.br/blog/seguranca-em-sistemas-de-login-senhas-e-cookies/#comments</comments>
		<pubDate>Thu, 23 Dec 2010 02:00:04 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Banco de Dados]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Segurança]]></category>
		<category><![CDATA[autenticação]]></category>
		<category><![CDATA[automático]]></category>
		<category><![CDATA[cookie]]></category>
		<category><![CDATA[criptografia]]></category>
		<category><![CDATA[hash]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[md-5]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[segurança]]></category>
		<category><![CDATA[senha]]></category>
		<category><![CDATA[sha-1]]></category>
		<category><![CDATA[sha1]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=263</guid>
		<description><![CDATA[Neste tutorial abordarei maneiras de criptografar senhas para serem usadas em sistemas de login. Também mostrarei uma possível forma de salvá-las em cookies, a fim de viabilizar login automático, porém sem salvar a senha ou o hash dela no cookie.]]></description>
			<content:encoded><![CDATA[<p>Neste tutorial abordarei maneiras de criptografar senhas para serem usadas em sistemas de login. Também mostrarei uma possível forma de salvá-las em <em>cookies</em>, a fim de viabilizar login automático, porém sem salvar a senha ou o <em>hash</em> dela no <em>cookie</em>.</p>
<p>Na verdade, &#8220;<b>criptografia</b>&#8221; não é a palavra correta aqui. Na verdade usaremos <em><b>hashes</b></em>, que é uma forma de codificação unidirecional, ou seja, não há como, a partir de um <em><b>hash</b></em>, obter o dado original. Afinal, não temos para que saber a senha do usuário. <b>Criptografia</b> é uma forma de codificação usando chaves, de forma que é possível obter o dado original, desde que tenha-se a chave com a qual o dado foi codificado.</p>
<p><span id="more-263"></span></p>
<h2>Sumário</h2>
<p><a href="#encode">Codificando senhas para salvá-las no banco de dados</a><br />
<a href="#salt">Usando Salt Number</a><br />
<a href="#cookie">Salvando a senha em cookie de forma segura</a><br />
<a href="#conclusao">Conclusão</a></p>
<h3><a name="encode">Codificando senhas para salvá-las no banco de dados</a></h3>
<p>Nos exemplos aqui mostrados usarei a linguagem PHP, mas os conceitos podem ser usados com qualquer linguagem de programação.</p>
<p>Por incrível que possa parecer, há muitas pessoas que salvam senhas puras no banco de dados, sem qualquer tipo de criptografia! Isso é um crime! Se alguém tiver acesso ao banco de dados, todos os usuários do sistemas estarão em risco. As senhas devem ser salvas criptografadas ou, como no nosso caso, em <em><b>hashes</b></em>.</p>
<p>Normalmente usa-se o <a href="http://pt.wikipedia.org/wiki/MD5" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/MD5?referer=');">MD5</a>, que gera uma saída de 32 caracteres. Porém, toda segurança é pouca. Temos o <a href="http://pt.wikipedia.org/wiki/Sha1" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/Sha1?referer=');">SHA-1</a>, que gera uma saída de 40 caracteres. A fim de evitar <a href="http://pt.wikipedia.org/wiki/Tabela_de_dispers%C3%A3o#Colis.C3.B5es" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/Tabela_de_dispers_C3_A3o_Colis.C3.B5es?referer=');">colisões</a>, devemos dar preferência ao SHA-1, uma vez que ele gera mais possibilidades de saídas.</p>
<p>Mas também podemos unir as duas! Uma possibilidade é esta:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> hashPasswd<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$passwd</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #990000;">sha1</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$passwd</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A função codifica com MD5 e depois codifica o resultado do MD5 com SHA-1. É uma segurança a mais, já que uma dicionário de senhas codificadas em SHA-1 provavelmente não contém <b>hashes</b> MD5 de senhas para serem testados.</p>
<p>Para ficar ainda mais seguro, você pode usar uma &#8220;<b>chave</b>&#8221; &#8211; não exatamente com o significado de uma chave de criptografia. Na verdade é uma string que concatenamos com a senha, a fim de gerar uma senha mais complexa:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'HASH_KEY'</span><span style="color: #339933;">,</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'chave secreta'</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> hashPasswdWithKey<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$passwd</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #990000;">sha1</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$passwd</span> <span style="color: #339933;">.</span> HASH_KEY <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>HASH_KEY é uma constante com o <em>hash</em> MD5 de uma string. Prefira usar uma string relativamente complexa, com números e caracteres maiúsculos e minúsculos no lugar de &#8220;chave secreta&#8221;.</p>
<p>O <em>hash</em> retornado é o valor que deve ser salvo no banco de dados.</p>
<p>Quando o usuário efetuar login, com nome de usuário e senha, basta pegarmos a senha informada, codificá-la com a nossa função e compará-la com o valor salvo no banco de dados.</p>
<h3><a name="salt">Usando Salt Number</a></h3>
<p>O uso de <a href="http://en.wikipedia.org/wiki/Salt_(cryptography)" onclick="urchinTracker('/outgoing/en.wikipedia.org/wiki/Salt_cryptography?referer=');">Salt Number</a> dificulta a realização de ataques por brute force, uma vez que aumenta exponencialmente as possibilidades de hash para uma mesma palavra.</p>
<p>Os links abaixo explicam detalhadamente como funcionam os salt numbers:<br />
<a href="http://www.vivaolinux.com.br/artigo/Armazenamento-de-senhas-no-Linux/?pagina=7" onclick="urchinTracker('/outgoing/www.vivaolinux.com.br/artigo/Armazenamento-de-senhas-no-Linux/?pagina=7&amp;referer=');">http://www.vivaolinux.com.br/artigo/Armazenamento-de-senhas-no-Linux/?pagina=7</a><br />
<a href="http://gravatai.ulbra.tche.br/~elgio/senhas.html" onclick="urchinTracker('/outgoing/gravatai.ulbra.tche.br/_elgio/senhas.html?referer=');">http://gravatai.ulbra.tche.br/~elgio/senhas.html</a></p>
<p>O Salt Numbeer é semelhante à HASH_KEY, que criamos anteriormente. Porém, em vez de usarmos uma constante, criamos um código aleatório para cada usuário. Esse valor fica salvo no banco de dados e é concatenado à senha do usuário, da mesma forma que fizemos com a constante HASH_KEY.</p>
<p>Uma possível forma de gerar códigos aleatórios para o Salt Number em PHP é esta:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Número de caracteres do Salt Number</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'SALT_SIZE'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">15</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Array com os 62 caracteres (a-z, A-Z, 0-9)</span>
<span style="color: #000088;">$amostra</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_merge</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">range</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'a'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'z'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">range</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'A'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Z'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">range</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">9</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Embaralha o array</span>
<span style="color: #990000;">shuffle</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$amostra</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$index</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_rand</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$amostra</span><span style="color: #339933;">,</span> SALT_SIZE <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$salt</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;</span> SALT_SIZE<span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$salt</span> <span style="color: #339933;">.=</span> <span style="color: #000088;">$amostra</span><span style="color: #009900;">&#91;</span> <span style="color: #000088;">$i</span> <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Assim, $salt contém o salt number gerado, para que seja usado na autenticação de um novo usuário recém-cadastrado.</p>
<h3><a name="cookie">Salvando a senha em cookie de forma segura</a></h3>
<p>A fim de permitirmos o <strong>login automático</strong>, muito comum em fóruns e lojas virtuais, precisamos usar <a href="http://pt.wikipedia.org/wiki/Cookie" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/Cookie?referer=');"><b>cookies</b></a>. Neles devem estar salvos os dados do usuário para autenticação no sistema.</p>
<p>Porém, não podemos colocar a senha do usuário no cookie. Mesmo que seja o hash da senha, pois fornecer acesso à hash salva no banco de dados é uma falha de segurança, já que ter um hash em mãos torna muito mais fácil um ataque por <em>brute force</em>. Por isso, vamos criar outro hash, baseado no hash da senha e no horário em que o usuário fez o último login.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'HASH_KEY'</span><span style="color: #339933;">,</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'chave secreta'</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'HASH_PATTERN'</span><span style="color: #339933;">,</span> HASH_KEY <span style="color: #339933;">.</span> <span style="color: #0000ff;">'%d'</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'%s'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> hashForCookie<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$strHash</span> <span style="color: #339933;">=</span> <span style="color: #990000;">sprintf</span><span style="color: #009900;">&#40;</span> HASH_PATTERN<span style="color: #339933;">,</span> <span style="color: #990000;">time</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #990000;">sha1</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$strHash</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Novamente temos a HASH_KEY, utilizada anteriormente. Criamos outra constante, a HASH_PATTERN, que é o padrão que será usado no hash. Aqui uso a chave (HASH_KEY), à qual são concatenados um &#8220;%d&#8221; e um &#8220;%s&#8221;, que serão substituídos pelo <em>timestamp</em> corrente e pelo hash da senha, respectivamente, usando sprintf(). A função retorna o SHA-1 da string final. </p>
<p>Essa função deve ser usada quando o usuário efetuar login. Assim que ele logar, salve no banco de dados (num campo diferente do da senha, claro) o hash gerado por <strong>hashForCookie</strong>. Esse é o dado que deverá ser salvo no cookie, além do nome do usuário, evitando salvar o hash da senha na máquina no usuário.</p>
<p>Para autenticar, verifique se o hash lido do cookie é o mesmo do salvo no banco de dados. Se for, autenticado, senão remova o cookie e solicite nome de usuário e senha. Assim que fizer login, gere o novo hash para o cookie, salvando-o no cookie, como citado anteriormente.</p>
<p>Uma forma simples de salvar esses dados num cookie usando PHP:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Beraldo'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$hash</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'2f9a922f0401476cd7089c235d76de5bb61150b9'</span><span style="color: #339933;">;</span> 
<span style="color: #000088;">$dados</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'user'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$user</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'passwd'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$hash</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">setcookie</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'nome_do_cookie'</span><span style="color: #339933;">,</span> <span style="color: #990000;">serialize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dados</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">time</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #cc66cc;">86400</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>A função <a href="http://php.net/manual/en/function.serialize.php" onclick="urchinTracker('/outgoing/php.net/manual/en/function.serialize.php?referer=');">serialize</a> serializa um objeto, retornando uma representação em string do mesmo. O caminho oposto pode ser feito com <a href="http://php.net/manual/en/function.unserialize.php" onclick="urchinTracker('/outgoing/php.net/manual/en/function.unserialize.php?referer=');">unserialize</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$cookie</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_COOKIE</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'nome_do_cookie'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$dados</span> <span style="color: #339933;">=</span> <span style="color: #990000;">unserialize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$cookie</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Assim, $dados é o array que definimos no código anterior.</p>
<h3><a name="conclusao">Conclusão</a></h3>
<p>Essas não são soluções finais para os dois casos apresentados. São apenas sugestões. É possível criar suas próprias funções, próprias criptografias etc.</p>
<p>O importante é procurar formas seguras de desenvolver sistemas.</p>
<p>Abraços,</p>
<p>Beraldo</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/seguranca-em-sistemas-de-login-senhas-e-cookies/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Links sobre a linguagem Python</title>
		<link>http://www.rberaldo.com.br/blog/links-sobre-a-linguagem-python/</link>
		<comments>http://www.rberaldo.com.br/blog/links-sobre-a-linguagem-python/#comments</comments>
		<pubDate>Tue, 16 Nov 2010 01:16:55 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Dicas]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[linguagem]]></category>
		<category><![CDATA[links]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=250</guid>
		<description><![CDATA[Alguns dos principais links com tutoriais e dicas sobre a linguagem de programação Python]]></description>
			<content:encoded><![CDATA[<p>Neste semestre, resolvi fazer um dos trabalhos da faculdade usando a linguagem Python. Há tempos eu ouvia que ela era uma linguagem muito poderosa, além de ser fácil de aprender.</p>
<p>Realmente a linguagem é excelente. Passei alguns scripts de PHP para Python e notei um desempenho bem melhor. Foi muito fácil e rápido aprender a linguagem. Apenas um dia de estudo já é suficiente para aprender o essencial, desde que já haja conhecimentos sobre programação, claro.</p>
<p>Encontrei alguns problemas com <em>threads</em> e a interrupção delas, com CTRL+C (SIGINT), mas isso não vem ao caso. =P</p>
<p>Gostaria de deixar aqui alguns links que me foram muito úteis para aprender Python. Espero que sejam úteis para quem quiser aprender a linguagem.</p>
<p>Aprenda Python em 10 minutos (em inglês):<br />
<a href="http://www.korokithakis.net/tutorials/python" target="_blank" onclick="urchinTracker('/outgoing/www.korokithakis.net/tutorials/python?referer=');">http://www.korokithakis.net/tutorials/python</a></p>
<p>Livro Dive Into Python (em inglês):<br />
<a href="http://diveintopython.org/" target="_blank" onclick="urchinTracker('/outgoing/diveintopython.org/?referer=');">http://diveintopython.org/</a></p>
<p>Tutorial do site oficial (em inglês):<br />
<a href="http://docs.python.org/tutorial/" target="_blank" onclick="urchinTracker('/outgoing/docs.python.org/tutorial/?referer=');">http://docs.python.org/tutorial/</a></p>
<p>Diversos links sobre Python no site brasileiro sobre a linuagem:<br />
<a href="http://www.python.org.br/wiki/DocumentacaoPython" onclick="urchinTracker('/outgoing/www.python.org.br/wiki/DocumentacaoPython?referer=');">http://www.python.org.br/wiki/DocumentacaoPython</a></p>
<p>Divirtam-se! =)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/links-sobre-a-linguagem-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Usando a classe nativa DateTime</title>
		<link>http://www.rberaldo.com.br/blog/php-usando-a-classe-nativa-datetime/</link>
		<comments>http://www.rberaldo.com.br/blog/php-usando-a-classe-nativa-datetime/#comments</comments>
		<pubDate>Thu, 14 Jan 2010 18:36:49 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=154</guid>
		<description><![CDATA[A partir do PHP 5.2.0, há uma maneira nativa e simples de se trabalhar com datas e horários, com ajuda da classe DateTime. Neste artigo, vou mostrar algumas das utilidades dessa classe.]]></description>
			<content:encoded><![CDATA[<p>A partir do PHP 5.2.0, há uma maneira nativa e simples de se trabalhar com datas e horários, com ajuda da classe <a href="http://br.php.net/manual/en/class.datetime.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/class.datetime.php?referer=');">DateTime</a>.</p>
<p>Neste artigo, vou mostrar algumas das utilidades dessa classe. Eu nunca a usei antes, estou aprendendo-a agora, enquanto monto o post. Logo, contribuições serão muito bem-vindas.</p>
<p>Vamos iniciar mostrando como funciona o construtor da classe.</p>
<p><span id="more-154"></span></p>
<p>Índice:<br />
<a href="#construct">1. Construtor da classe</a><br />
<a href="#format">2. Formatando datas</a><br />
<a href="#add">3. Adicionando períodos a datas</a><br />
<a href="#sub">4. Subtraindo períodos de uma data</a><br />
<a href="#diff">5. Calculando diferença entre datas</a><br />
<a href="#set">6. Modificando a data e a hora do objeto</a></p>
<h3><a name="construct">1. Construtor da classe</a></h3>
<p>Sintaxe do construtor:</p>
<p> <strong>DateTime::__construct  ([ string $time = "now"  [, DateTimeZone $timezone = NULL  ]] )</strong></p>
<p>Esse método aceita dois parâmetros, ambos opcionais. O primeiro é a data/hora, no mesmo formato aceito pela função <a href="http://br2.php.net/strftime" target="_blank" onclick="urchinTracker('/outgoing/br2.php.net/strftime?referer=');">strftime()</a>. O segundo consiste no <em>timezone</em> que deve ser utilizado. Ele deve ser uma instância da classe <a href="http://br2.php.net/manual/en/class.datetimezone.php" target="_blank" onclick="urchinTracker('/outgoing/br2.php.net/manual/en/class.datetimezone.php?referer=');">DateTimeZone</a>. Outra maneira de definir o <em>timezone</em> é por meio da função <a href="http://br.php.net/date_default_timezone_set" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/date_default_timezone_set?referer=');">date_default_timezone_set()</a>.</p>
<p>Ambas as classes DateTime e DateTimeZone disparam uma exceção se seus construtores receberem parâmetro inválidos. Logo, podemos usar blocos try/catch para instanciar essas classes.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">try
<span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$DateTime</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'now'</span><span style="color: #339933;">,</span> <span style="color: #000000; font-weight: bold;">new</span> DateTimeZone<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'America/Sao_Paulo'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
catch<span style="color: #009900;">&#40;</span> Exception <span style="color: #000088;">$e</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Erro ao instanciar objeto.&lt;br /&gt;'</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$e</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #990000;">exit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Experimente trocar o &#8220;now&#8221; por um valor não aceito pelo método, como uma string qualquer. Uma exceção será disparada.</p>
<h3><a name="format">2. Formatando datas</a></h3>
<p>Para formatar datas, usamos o método <em>format</em>, que aceita um parâmetro, correspondente a uma formatação de data aceita pela função <a href="http://br.php.net/manual/en/function.date.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/function.date.php?referer=');">date()</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$DateTime</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y H:i:s&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;Y-m-d H:i:s&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;Y/m/d H:i:s&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span></pre></div></div>

<h3><a name="add">3. Adicionando períodos a datas</a></h3>
<p>Com o método <em>add()</em>, podemos adicionar períodos à data salva no objeto DateTime. É possível adicionar períodos de dias, períodos de tempo ou ambos, seguindo a formatação aceita pelo método, que recebe um único parâmetro, o qual é uma instância da classe <a href="http://br.php.net/manual/en/class.dateinterval.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/class.dateinterval.php?referer=');">DateInterval</a>, responsável por manipular os dados do período especificado. </p>
<p>Os períodos são especificados da seguinte maneira: períodos de dias são precedidos pela letra &#8220;P&#8221;, seguidas de inteiros e seus respectivos identificadores de tempo (&#8220;D&#8221; para dias, &#8220;M&#8221; para meses e &#8220;Y&#8221; para anos). Períodos de tempo são precedidos pela letra &#8220;T&#8221; e seguidos de inteiros e seus respectivos identificadores de unidade (&#8220;H&#8221; para horas, &#8220;M&#8221; para minutos e &#8220;S&#8221; para segundos).</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$DateTime</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateInterval<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;P30D&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// adiciona 30 dias</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateInterval<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;P2M&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// adiciona 2 meses</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateInterval<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;P5Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// adiciona 5 anos</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">add</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateInterval<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;P5Y2M30D&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// adiciona 30 dias, 2 meses e 5 anos</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span></pre></div></div>

<p>Note que cada adição é feita com base na adição anterior, uma vez que cada soma modifica a data armazenada no objeto.</p>
<h3><a name="sub">4. Subtraindo períodos de uma data</a></h3>
<p>O método <em>sub</em> funciona da mesma forma que o <em>add</em>, com a mesma lista de parâmetros, mas, logicamente, em vez de adicionar períodos, ele os subtrai.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$DateTime</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sub</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateInterval<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;P30D&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// subtrai 30 dias</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sub</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateInterval<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;P2M&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// subtrai 2 meses</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sub</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateInterval<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;P5Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// subtrai 5 anos</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sub</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateInterval<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;P5Y2M30D&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// subtrai 30 dias, 2 meses e 5 anos</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span></pre></div></div>

<h3><a name="diff">5. Calculando diferença entre datas</a></h3>
<p>Usando o método <em>diff</em>, podemos calcular o intervalo entre duas datas, com precisão de dias, meses, anos, horas, minutos e segundos. Esse método retorna uma instância da classe DateInterval, já citada anteriormente neste artigo.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$DateTime</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$diff</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">diff</span><span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'2009-02-14'</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Diferença de:&lt;br /&gt;
&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$diff</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">d</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; dias&lt;br /&gt;
&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$diff</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">m</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; meses&lt;br /&gt;
&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$diff</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">y</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; anos&lt;br /&gt;
&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$diff</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">h</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; horas&lt;br /&gt;
&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$diff</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">i</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; minutos&lt;br /&gt;
&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$diff</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">s</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot; segundos&lt;br /&gt;
&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<h3><a name="set">6. Modificando a data e a hora do objeto</a></h3>
<p>Para modificar a data e a hora armazenadas no objeto, utilizamos os métodos <em>setDate</em> e <em>setTime</em>.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$DateTime</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y H:i&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setDate</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">2007</span><span style="color: #339933;">,</span> <span style="color: #208080;">07</span><span style="color: #339933;">,</span> <span style="color: #208080;">07</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setTime</span><span style="color: #009900;">&#40;</span> <span style="color: #208080;">07</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">27</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$DateTime</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">format</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;d/m/Y H:i&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;br /&gt;'</span><span style="color: #339933;">;</span></pre></div></div>

<p>Espero que tenha ficado tudo claro para todos. A utilização das classes não é difícil. Mais informações podem ser obtidas na documentação oficial.</p>
<p>Link úteis:<br />
<a href="http://br.php.net/manual/en/class.datetime.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/class.datetime.php?referer=');">Documentação da classe DateTime</a><br />
<a href="http://br.php.net/manual/en/class.datetimezone.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/class.datetimezone.php?referer=');">Documentação da classe DateTimeZone</a><br />
<a href="http://br.php.net/manual/en/class.dateinterval.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/class.dateinterval.php?referer=');">Documentação da classe DateTimeInterval</a><br />
<a href="http://br.php.net/manual/en/ref.datetime.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/ref.datetime.php?referer=');">Funções de data e hora do PHP</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/php-usando-a-classe-nativa-datetime/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Criando combos (select&#8217;s) dinâmicos com valores padrões</title>
		<link>http://www.rberaldo.com.br/blog/criando-combos-dinamicos-com-valores-padroes/</link>
		<comments>http://www.rberaldo.com.br/blog/criando-combos-dinamicos-com-valores-padroes/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 19:44:20 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[combo]]></category>
		<category><![CDATA[dados]]></category>
		<category><![CDATA[dinâmico]]></category>
		<category><![CDATA[padrão]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=151</guid>
		<description><![CDATA[Uma dúvida muito comum - porém de solução bastante simples - é como criar um combo (select) dinâmico e com um valor padrão. Isso pode ser útil ao montar um formulário para edição de dados.]]></description>
			<content:encoded><![CDATA[<p>Uma dúvida muito comum &#8211; porém de solução bastante simples &#8211; é como criar um combo (select) dinâmico e com um valor padrão. Isso pode ser útil ao montar um formulário para edição de dados. Suponha que você possui um sistema em que o usuário escolhe uma dentre diversas opções, por meio de um combo. Para criar um formulário de edição, você deve exibir o combo, mas mostrando a seleção atual.</p>
<p>Para exemplificar, vou usar um simples array com alguns estados brasileiros e uma variável que armazenará o dado que deve aparecer selecionado.</p>
<p><span id="more-151"></span></p>
<p>A exibição do combo, juntamente com o dado selecionado, será realizada por uma função, que percorre o array de dados e compara se o registro corrente é igual ao que deve ser selecionado. Se a comparação retornar TRUE, insere-se o atributo &#8220;selected&#8221; na tag &#8220;option&#8221;.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$estados</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'PR'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'SP'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'RJ'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'SC'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'RS'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$padrao</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'PR'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> MontaSelect<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$estados</span><span style="color: #339933;">,</span> <span style="color: #000088;">$padrao</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> MontaSelect<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dados</span><span style="color: #339933;">,</span> <span style="color: #000088;">$selected</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">NULL</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&lt;select name=<span style="color: #000099; font-weight: bold;">\&quot;</span>uf<span style="color: #000099; font-weight: bold;">\&quot;</span> id=<span style="color: #000099; font-weight: bold;">\&quot;</span>uf<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000088;">$total</span><span style="color: #339933;">=</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dados</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$total</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$str</span> <span style="color: #339933;">.=</span> <span style="color: #0000ff;">&quot;&lt;option value=<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$dados</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933;">.</span> <span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dados</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$selected</span> <span style="color: #009900;">&#41;</span> ? <span style="color: #0000ff;">&quot; selected=<span style="color: #000099; font-weight: bold;">\&quot;</span>true<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&gt;&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$dados</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;/option&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000088;">$str</span> <span style="color: #339933;">.=</span> <span style="color: #0000ff;">&quot;&lt;/select&gt;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>A solução é simples, apesar de ser fonte de dúvida frequente em fóruns pela Internet.</p>
<p>Lembrando que é sempre bom efetuar verificação nos tipos de parâmetros da função. Não inseri isso no código, mas é recomendável usar is_array() para verificar a variável $dados, por exemplo, a fim de evitar geração de erros e warnings.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/criando-combos-dinamicos-com-valores-padroes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dica: Tutorial para iniciantes em Zend Framework</title>
		<link>http://www.rberaldo.com.br/blog/dica-tutorial-para-iniciantes-em-zend-framework/</link>
		<comments>http://www.rberaldo.com.br/blog/dica-tutorial-para-iniciantes-em-zend-framework/#comments</comments>
		<pubDate>Sun, 18 Oct 2009 19:08:49 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Dica]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Zend]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=109</guid>
		<description><![CDATA[O Zend Framework é um dos frameworks mais conhecidos e utilizados com PHP. Neste post, é indicado um link com um tutorial básico sobre essa ferramenta.]]></description>
			<content:encoded><![CDATA[<p>O <a href="http://framework.zend.com" target="_blank" title="Zend Framework" onclick="urchinTracker('/outgoing/framework.zend.com?referer=');">Zend Framework</a> é um dos frameworks mais conhecidos e utilizados com PHP. Por muito tempo quis começar a estudar essa ferramenta, porém sempre faltava tempo ou apareciam outras coisas para fazer. Nesta semana resolvi começar a estudar essa ferramenta. Já estava mais do que na hora de fazer isso.</p>
<p><span id="more-109"></span><br />
Usei um ótimo tutorial para iniciantes e gostaria de compartilhar o link com vocês. O post é constantemente atualizado, conforme saem novas versões do Zend Framework.</p>
<p><a title="Getting Started With Zend Framework" href="http://akrabat.com/zend-framework-tutorial" target="_blank" onclick="urchinTracker('/outgoing/akrabat.com/zend-framework-tutorial?referer=');">Getting Started With Zend Framework</a></p>
<p>Como o nome diz, é apenas um tutorial para mostrar o funcionamento básico. Mas é o suficiente para desenvolver uma aplicação simples e perder o medo do Zend Framework, que parece complexo logo de cara.</p>
<p>Espero que o link lhes seja útil.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/dica-tutorial-para-iniciantes-em-zend-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reduzir imagens mantendo a proporção</title>
		<link>http://www.rberaldo.com.br/blog/reduzir-imagens-mantendo-a-proporcao/</link>
		<comments>http://www.rberaldo.com.br/blog/reduzir-imagens-mantendo-a-proporcao/#comments</comments>
		<pubDate>Mon, 12 Oct 2009 03:46:50 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[GD]]></category>
		<category><![CDATA[miniatura]]></category>
		<category><![CDATA[proporção]]></category>
		<category><![CDATA[thumbnail]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=92</guid>
		<description><![CDATA[Muita gente tem dúvida em como reduzir uma imagem mantendo a proporção entre largura e altura. Neste artigo é exibida uma solução simples para esse problema.]]></description>
			<content:encoded><![CDATA[<p>Muita gente tem dúvida em como reduzir uma imagem mantendo a proporção entre largura e altura. A solução é simples. Lógica pura. Matemática, na verdade. :P</p>
<p><span id="more-92"></span><br />
Vamos a um exemplo simples e explicado.</p>
<p>Definimos o caminho à imagem a ser reduzida:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// imagem a ser reduzida</span>
<span style="color: #000088;">$foto</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'foto2.jpg'</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Definimos as dimensões máximas da imagem</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// dimensões máximas da imagem, em pixels (largura e altura)</span>
<span style="color: #000088;">$tamMax</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">200</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">240</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Usando a função getimagesize(), do PHP, obtemos a largura, a altura e o tipo da imagem:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// 0 =&gt; largura</span>
<span style="color: #666666; font-style: italic;">// 1 =&gt; Altura</span>
<span style="color: #666666; font-style: italic;">// 2 =&gt; Formato da imagem</span>
<span style="color: #990000;">list</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$imgLarg</span><span style="color: #339933;">,</span> <span style="color: #000088;">$imgAlt</span><span style="color: #339933;">,</span> <span style="color: #000088;">$imgTipo</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$foto</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Esta parte faz o cálculo das novas dimensões da imagem</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// verifica se a imagem é maior que o máximo permitido</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$imgLarg</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$tamMax</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$imgAlt</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$tamMax</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// verifica se a largura é maior que a altura</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$imgLarg</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$imgAlt</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$novaLargura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$tamMax</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$novaAltura</span> <span style="color: #339933;">=</span> <span style="color: #990000;">round</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$novaLargura</span> <span style="color: #339933;">/</span> <span style="color: #000088;">$imgLarg</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #000088;">$imgAlt</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">// se a altura for maior que a largura</span>
	<span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$imgAlt</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$imgLarg</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$novaAltura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$tamMax</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$novaLargura</span> <span style="color: #339933;">=</span> <span style="color: #990000;">round</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$novaAltura</span> <span style="color: #339933;">/</span> <span style="color: #000088;">$imgAlt</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #000088;">$imgLarg</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">// altura == largura</span>
	<span style="color: #b1b100;">else</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$novaAltura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$novaLargura</span> <span style="color: #339933;">=</span> <span style="color: #990000;">max</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$tamMax</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">else</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;não é necessário redimensionar&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #990000;">exit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Por fim, criamos as imagens, fazemos o redimensionamento e exibimos a imagem desejada no navegador:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// cria a imagem baseada na imagem original</span>
<span style="color: #000088;">$srcImg</span> <span style="color: #339933;">=</span> <span style="color: #990000;">imagecreatefromjpeg</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$foto</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// cria a nova imagem</span>
<span style="color: #000088;">$destImg</span> <span style="color: #339933;">=</span> <span style="color: #990000;">imagecreatetruecolor</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$novaLargura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$novaAltura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// copia para a imagem de destino a imagem original redimensionada</span>
<span style="color: #990000;">imagecopyresampled</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$destImg</span><span style="color: #339933;">,</span> <span style="color: #000088;">$srcImg</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #000088;">$novaLargura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$novaAltura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$imgLarg</span><span style="color: #339933;">,</span> <span style="color: #000088;">$imgAlt</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// cabeçalho para exibir a imagem no navegador.</span>
<span style="color: #666666; font-style: italic;">// se for salvar em arquivo, não é necessário</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'content-type: image/jpeg'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// exibe a imagem</span>
<span style="color: #990000;">imagejpeg</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$destImg</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// destrói as imagens geradas</span>
<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$destImg</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$srcImg</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Usei funções específicas para jpeg pois, nesse caso, usei uma imagem definida no script. Para criar um script genérico, você pode usar o terceiro elemento do array retornado por getimagesize(), a fim de chamar uma função conforme o tipo da imagem. Isso pode ser feito com o auxílio da função call_user_func.</p>
<p>Post simples. Apenas para sanar uma dúvdia recorrente por aí.<br />
Solução simples. :)</p>
<p>Links úteis:<br />
<a title="Referência das funções da biblioteca GD" href="http://br2.php.net/manual/pt_BR/book.image.php" target="_blank" onclick="urchinTracker('/outgoing/br2.php.net/manual/pt_BR/book.image.php?referer=');"> Referência das funções da biblioteca GD</a><br />
<a title="Documentação da função call_user_func" href="http://br2.php.net/manual/pt_BR/function.call-user-func.php" target="_blank" onclick="urchinTracker('/outgoing/br2.php.net/manual/pt_BR/function.call-user-func.php?referer=');"> Documentação da função call_user_func</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/reduzir-imagens-mantendo-a-proporcao/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Como criar sistema de BBCode</title>
		<link>http://www.rberaldo.com.br/blog/como-criar-sistema-de-bbcode/</link>
		<comments>http://www.rberaldo.com.br/blog/como-criar-sistema-de-bbcode/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 12:34:08 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[bbcode]]></category>
		<category><![CDATA[formatação de texto]]></category>
		<category><![CDATA[tags]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=61</guid>
		<description><![CDATA[O BBCode é um recurso amplamente utilizado em fóruns. Ele permite editar textos de forma simples e rápida, sendo de fácil compreensão inclusive para leigos em HTML. Neste post mostrarei como criar alguns BBCodes mais usados, como [b] (negrito), [i] (itálico), [img] (imagem), [url] (link), [youtube] (para vídeos do youtube) e outros. Basicamente, o que [...]]]></description>
			<content:encoded><![CDATA[<p>O <a href="http://pt.wikipedia.org/wiki/BBCode" target="_blank" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/BBCode?referer=');">BBCode</a> é um recurso amplamente utilizado em fóruns. Ele permite editar textos de forma simples e rápida, sendo de fácil compreensão inclusive para leigos em HTML.</p>
<p>Neste post mostrarei como criar alguns BBCodes mais usados, como [b] (negrito), [i] (itálico), [img] (imagem), [url] (link), [youtube] (para vídeos do youtube) e outros.</p>
<p><span id="more-61"></span><br />
Basicamente, o que precisamos para montar o sistema de BBCode é usar funções de reposicionamento (<em>replace</em>) de textos, utilizando <a href="http://pt.wikipedia.org/wiki/Express%C3%A3o_regular" target="_blank" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/Express_C3_A3o_regular?referer=');">Expressões Regulares</a> (ER&#8217;s), a fim de modificar apenas uma parte da string, sem perder o dado principal contido nela &#8211; o conteúdo a ser exibido com formatação.</p>
<p>Vamos começar com exemplos simples.</p>
<h3>Negrito e Itálico</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// exemplo 1</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'exemplo de texto em [b]negrito[/b] para testar BBCode'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[b\](.*?)\[\/b\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;strong&gt;<span style="color: #006699; font-weight: bold;">$1</span>&lt;/strong&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// exemplo 2</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'exemplo de texto em [b]negrito[/b] para testar BBCode'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[(\/)?b\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;<span style="color: #006699; font-weight: bold;">$1strong</span>&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A vantagem do primeiro exemplo é que, se o usuário esquecer de fechar a tag, por exemplo, o texto não ficará totalmente em negrito. Teste o segundo exemplo com a string abaixo e veja o resultado.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'exemplo de texto em [b]negrito[/b para testar BBCode'</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A ER irá casar (<em>match</em>) com &#8220;[b]&#8220;, inserindo a tag <strong>. Porém, não encontrará o fechamento &#8220;[/b]&#8220;, para inserir a tag </strong>. Assim, todo o texto seguinte ficará em negrito.</p>
<p>O BBCode para itálico é praticamente igual. Basta mudar [b]  para [i] e <strong> para <em>.</p>
<h3>Imagens</h3>
<p>Para inserir imagens, geralmente é usada a seguinte sintaxe:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#91;</span>img<span style="color: #009900;">&#93;</span>http<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">//url_da_imagem.jpg[/img]</span></pre></td></tr></table></div>

<p>Nesse caso, usaremos o seguinte trecho para transformarmos o BBCode em HTML:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'[img]http://www.inf.ufpr.br/rbc08/linux_user_id.png[/img]'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[img\](.*?)\[\/img\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;img src=<span style="color: #000099; font-weight: bold;">\&quot;</span><span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span> alt=<span style="color: #000099; font-weight: bold;">\&quot;</span>texto_alternativo<span style="color: #000099; font-weight: bold;">\&quot;</span> /&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A ER captura o conteúdo entre as tags [img] e [/img] e o insere no atributo src da tag img.</p>
<h3>Links</h3>
<p>Vamos assumir que o BBCode para link seja da seguinte forma:</p>
<pre>
[url=http://url_desejada]Texto que será exibido como link[/url]
</pre>
<p>Para essa situação, devemos casar duas string: a URL e o texto a ser exibido. Logo, usaremos o seguinte código:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'[url=http://www.rberaldo.com.br]Blog do Beraldo[/url]'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[url=(.*?)\](.*?)\[\/url\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;a href=<span style="color: #000099; font-weight: bold;">\&quot;</span><span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span> target=<span style="color: #000099; font-weight: bold;">\&quot;</span>blank<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;<span style="color: #006699; font-weight: bold;">$2</span>&lt;/a&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Adicionei o atributo target para evitar que o link seja exibido na mesma página. Você pode retirá-lo. Também pode adicionar outros atributos, como <strong>rel</strong>, a fim de definir a relação do link com sua página.</p>
<h3>Texto colorido</h3>
<p>Para colorir textos, usaremos o BBCode [color=cor_desejada][texto[/color].</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'[color=red]texto vermelho[/color]'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[color=(.*?)\](.*?)\[\/color\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;spen style=<span style="color: #000099; font-weight: bold;">\&quot;</span>color: <span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;<span style="color: #006699; font-weight: bold;">$2</span>&lt;/span&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>É possível usar nomes de cores, como green, red, blue, black etc, ou o código hexadecimal dela, no padrão #123456. </p>
<h3>Vídeos do Youtube</h3>
<p>O Youtube disponibiliza em sua página o código-fonte do vídeo exibido, a fim de permitir que você o insira em sua página. Logo, também podemos criar um BBCode para inserir vídeos, bastando inserir o código <strong>embed</strong> (incorporar) mostrado na página do Youtube, junto ao player do vídeo, como mostra a imagem abaixo:</p>
<p><img src="http://rberaldo.com.br/blog/img/youtube_embed.png" alt="Como copiar código para incorporar vídeo do youtube à sua página" /></p>
<p>O código para postagem é basicamente este:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>object width<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;425&quot;</span> height<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;344&quot;</span><span style="color: #339933;">&gt;</span>
	<span style="color: #339933;">&lt;</span>param name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;movie&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;http://www.youtube.com/v/codigo_do_video&quot;</span><span style="color: #339933;">&gt;&lt;/</span>param<span style="color: #339933;">&gt;</span>
	<span style="color: #339933;">&lt;</span>param name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;allowFullScreen&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;true&quot;</span><span style="color: #339933;">&gt;&lt;/</span>param<span style="color: #339933;">&gt;</span>
	<span style="color: #339933;">&lt;</span>param name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;allowscriptaccess&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;always&quot;</span><span style="color: #339933;">&gt;&lt;/</span>param<span style="color: #339933;">&gt;</span>
	<span style="color: #339933;">&lt;</span>embed src<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;http://www.youtube.com/v/codigo_do_video&quot;</span> type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;application/x-shockwave-flash&quot;</span> allowscriptaccess<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;always&quot;</span> allowfullscreen<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;true&quot;</span> width<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;425&quot;</span> height<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;344&quot;</span><span style="color: #339933;">&gt;&lt;/</span>embed<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>object<span style="color: #339933;">&gt;</span></pre></div></div>

<p>Logo, basta inserirmos o código do vídeo onde está a string &#8220;codigo_do_video&#8221;.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// string que será usada no reposicionamento</span>
<span style="color: #000088;">$replace</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;
&lt;object width=<span style="color: #000099; font-weight: bold;">\&quot;</span>425<span style="color: #000099; font-weight: bold;">\&quot;</span> height=<span style="color: #000099; font-weight: bold;">\&quot;</span>344<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;
	&lt;param name=<span style="color: #000099; font-weight: bold;">\&quot;</span>movie<span style="color: #000099; font-weight: bold;">\&quot;</span> value=<span style="color: #000099; font-weight: bold;">\&quot;</span>http://www.youtube.com/v/<span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;/param&gt;
	&lt;param name=<span style="color: #000099; font-weight: bold;">\&quot;</span>allowFullScreen<span style="color: #000099; font-weight: bold;">\&quot;</span> value=<span style="color: #000099; font-weight: bold;">\&quot;</span>true<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;/param&gt;
	&lt;param name=<span style="color: #000099; font-weight: bold;">\&quot;</span>allowscriptaccess<span style="color: #000099; font-weight: bold;">\&quot;</span> value=<span style="color: #000099; font-weight: bold;">\&quot;</span>always<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;/param&gt;
	&lt;embed src=<span style="color: #000099; font-weight: bold;">\&quot;</span>http://www.youtube.com/v/<span style="color: #006699; font-weight: bold;">$1</span><span style="color: #000099; font-weight: bold;">\&quot;</span> type=<span style="color: #000099; font-weight: bold;">\&quot;</span>application/x-shockwave-flash<span style="color: #000099; font-weight: bold;">\&quot;</span> allowscriptaccess=<span style="color: #000099; font-weight: bold;">\&quot;</span>always<span style="color: #000099; font-weight: bold;">\&quot;</span> allowfullscreen=<span style="color: #000099; font-weight: bold;">\&quot;</span>true<span style="color: #000099; font-weight: bold;">\&quot;</span> width=<span style="color: #000099; font-weight: bold;">\&quot;</span>425<span style="color: #000099; font-weight: bold;">\&quot;</span> height=<span style="color: #000099; font-weight: bold;">\&quot;</span>344<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&lt;/embed&gt;
&lt;/object&gt;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'[youtube]http://www.youtube.com/watch?v=YaXLlyEm4kQ&amp;feature=rec-HM-r2[/youtube]'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/\[youtube\].+?watch\?v=([^&amp;]+).*?\[\/youtube\]/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$replace</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$str</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Criei a variável $replace para facilitar a visualização do código que será usado no <em>replace</em>. A ER desse exemplo é um pouco mais complexa, mas não é tão difícil de compreendê-la. &#8220;.+?&#8221; casa com &#8220;http://&#8221; até qualquer coisa antes de &#8220;watch&#8221;. &#8220;([^&#038;]+)&#8221; pega o código do vídeo, que não pode contar o caractere &#8220;&amp;&#8221;, que é o delimitador de variáveis da URL. Após o código do vídeo, pode ou não haver outras variáveis, por isso termina-se com &#8220;.*?&#8221;.</p>
<p>Lógica semelhante pode ser usada para Google Vídeos ou outros sites afins.</p>
<p>É possível criar BBCodes para diversas outras finalidades. Basta ter criatividade e conhecimento de ER&#8217;s, para saber montar as regras de reposicionamento.</p>
<p>Alguns links interessantes:<br />
<a href="http://guia-er.sourceforge.net" target="_blank" onclick="urchinTracker('/outgoing/guia-er.sourceforge.net?referer=');">Guia sobre Expressões Regulares</a><br />
<a href="http://br.php.net/manual/en/function.preg-replace.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/en/function.preg-replace.php?referer=');">Documentação da função preg_replace</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/como-criar-sistema-de-bbcode/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Técnicas de CAPTCHA</title>
		<link>http://www.rberaldo.com.br/blog/tecnicas-de-captcha/</link>
		<comments>http://www.rberaldo.com.br/blog/tecnicas-de-captcha/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 00:02:39 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[acessibilidade]]></category>
		<category><![CDATA[captcha]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=53</guid>
		<description><![CDATA[CAPTCHA é um recurso amplamente usado nos dias de hoje. Porém, seu mau uso gera conteúdo inacessível a usuários com deficiência visual ou deficiência de aprendizagem.]]></description>
			<content:encoded><![CDATA[<p>CAPTCHA (<em>Completely Automated Public Turing test to tell Computers and Humans Apart</em>) é um recurso amplamente usado nos dias de hoje. Porém, seu mau uso gera conteúdo inacessível a usuários com deficiência visual ou deficiência de aprendizagem, como dislexia.</p>
<p>CAPTCHA consiste em um teste para verificar se quem está acessando o site é, deveras, um ser humano e não um robô (como um bot de busca ou de spam). Normalmente é exibida uma imagem com letras e números distorcidos, os quais devem ser digitados pelo usuário numa caixa de texto. Apesar de ser o mais usado, é o menos acessível.</p>
<p><span id="more-53"></span><br />
<img src="http://www.rberaldo.com.br/blog/img/captcha-sample.gif" alt="Exemplos de imagens de captcha" /><br />
<em>Exemplos de imagens de CAPTCHA</em></p>
<p>Porém, há diversas outras formas de se fazer uma verificação CAPTCHA. Por exemplo, é possível gerar contas matemáticas simples, para que o usuário forneça a resposta. Também é possível adicionar campos <em>hidden</em> (ocultos) ou campos invisíveis via CSS (numa div com &#8220;display:none&#8221;, por exemplo). Um ser humano não preencherá esses campos, logo, se forem enviados com valores diferentes de vazio, conclui-se que o usuário é um bot.</p>
<p>Vamos a alguns exemplos simples.</p>
<p><strong>Usando o método comum, de imagem</strong></p>
<p>form.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>form method<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;post&quot;</span> action<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;verifica.php&quot;</span><span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>p<span style="color: #339933;">&gt;</span>Digite o código exibido na imagem<span style="color: #339933;">&lt;/</span>p<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>input type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;text&quot;</span> name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;codigo&quot;</span> id<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;codigo&quot;</span> <span style="color: #339933;">/&gt;</span>
<span style="color: #339933;">&lt;</span>img src<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;img.php&quot;</span> <span style="color: #339933;">/&gt;</span>
<span style="color: #339933;">&lt;</span>input type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;submit&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;enviar&quot;</span> <span style="color: #339933;">/&gt;</span>
<span style="color: #339933;">&lt;/</span>form<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>img.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #990000;">session_start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'codigo'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">rand</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">1111</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">9999</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$im</span> <span style="color: #339933;">=</span> <span style="color: #990000;">imagecreate</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">45</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">20</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$background_color</span> <span style="color: #339933;">=</span> <span style="color: #990000;">imagecolorallocate</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$im</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">255</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">255</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">255</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$text_color</span> <span style="color: #339933;">=</span> <span style="color: #990000;">imagecolorallocate</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$im</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">255</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">15</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">40</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">imagestring</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$im</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">15</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'codigo'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$text_color</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;Content-type: image/png&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">imagepng</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$im</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$im</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>verifica.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #990000;">session_start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'codigo'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'codigo'</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;código correto&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">else</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;código errado&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #990000;">session_destroy</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Esse exemplo é bem simples, apenas o básico do sistema. Dá para melhorar a imagem, criptografar o código na sessão, a fim de evitar que o número seja visualizado por meio de scripts ou códigos maliciosos, com o intuito de burlar a identificação. </p>
<p><strong>Gerando contas matemáticas simples</strong></p>
<p>Também é possível gerar alguns cálculos matemáticos simples, para verificar se o usuário não é um bot. Um exemplo simples:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// operando 1</span>
<span style="color: #000088;">$op1</span> <span style="color: #339933;">=</span> <span style="color: #990000;">rand</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">20</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// operando 2</span>
<span style="color: #000088;">$op2</span> <span style="color: #339933;">=</span> <span style="color: #990000;">rand</span><span style="color: #009900;">&#40;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">20</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// operador</span>
<span style="color: #000088;">$operador</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'+'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'-'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'*'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'/'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$operador</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$operador</span><span style="color: #009900;">&#91;</span> <span style="color: #990000;">array_rand</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$operador</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$expressao</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$op1</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$operador</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$op2</span><span style="color: #339933;">;</span>
<span style="color: #990000;">eval</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\$</span>valor = <span style="color: #006699; font-weight: bold;">$op1</span> <span style="color: #006699; font-weight: bold;">$operador</span> <span style="color: #006699; font-weight: bold;">$op2</span>;&quot;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$expressao</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' = '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$valor</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Nesse caso, bastaria comparar o conteúdo de $valor com o número enviado pelo formulário. Claro que dá para fazer melhorias, como verificar se, quando for divisão, o resultado é inteiro, ou verificar se uma subtração não gera números negativos etc.</p>
<p><strong>Campos ocultos</strong></p>
<p>Uma forma que conheci há uns dias é verificar o preenchimento de campos ocultos. Geralmente os bots preenchem todos os campos encontrados no código-fonte HTML. Logo, também preencherá um campo oculto. Se isso ocorrer, saberemos que ele é um robô.</p>
<p>É possível usar um campo do tipo hidden ou um text comum, oculto via CSS. A vantagem de um campo text oculto por CSS é a dificuldade de o bot descobrir que o campo é invisível. Um campo do tipo hidden é facilmente identificado no código-fonte. Porém, podemos usar o seguinte código:</p>
<pre class="brush:html">
<div class="oculta">
<input type="text" name="nome_do_campo" id="id_do_campo" />
</div>
</pre>
<p>E definiremos a classe CSS &#8220;oculta&#8221; num arquivo CSS à parte, a fim de dificultar a leitura do bot:</p>
<pre class="brush:css">
.oculta
{
    display: none;
}
</pre>
<p>Assim o campo será lido pelo bot como um campo de texto comum, mas ele não saberá que é oculto, logo o preencherá.</p>
<p>Essas foram apenas algumas técnicas alternativas à tradicional imagem de autenticação. Pesquisando no Google, há diversas outras opções, mas a  lógica não difere muito da apresentada aqui.</p>
<p>Links interessantes:<br />
<a href="http://www.maujor.com/w3c/turingtest.html" target="_blank" onclick="urchinTracker('/outgoing/www.maujor.com/w3c/turingtest.html?referer=');">http://www.maujor.com/w3c/turingtest.html</a><br />
<a href="http://www.captcha.net" target="_blank" onclick="urchinTracker('/outgoing/www.captcha.net?referer=');">http://www.captcha.net</a><br />
<a href="http://recaptcha.net" target="_blank" onclick="urchinTracker('/outgoing/recaptcha.net?referer=');">http://recaptcha.net</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/tecnicas-de-captcha/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Classe PHP para Manipulação de Imagens</title>
		<link>http://www.rberaldo.com.br/blog/classe-php-para-manipulacao-de-imagens/</link>
		<comments>http://www.rberaldo.com.br/blog/classe-php-para-manipulacao-de-imagens/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 13:40:00 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Imagens]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Class]]></category>
		<category><![CDATA[Classe]]></category>
		<category><![CDATA[GD]]></category>
		<category><![CDATA[Manipulação de Imagens]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/2009/07/30/classe-php-para-manipulacao-de-imagens/</guid>
		<description><![CDATA[Classe PHP destinada à manipulação de imagens, com opções para criação de miniaturas (thumbnails) e inserção de marca d'água.]]></description>
			<content:encoded><![CDATA[<p>Fiz uma classe PHP para manipulação de imagens. Ela salva imagens (de diretórios ou de um formulário &#8211; envio por POST), cria miniaturas (thumbnails) e insere logomarca (marca d&#8217;água).</p>
<p><span id="more-22"></span></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * Arquivo com a classe \c ImgHandler.
 * @file class.ImgHandler.php
*/</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">/*
 * Exemplo de uso:
 *
 * $img = 'foto.jpg'; // foto que deverá ser salva/redimensionada
 * $ImgHandler = new ImgHandler();
 * $foto = $ImgHandler-&gt;saveImg( $img );
 * $ImgHandler-&gt;createThumb( $foto );
 * $ImgHandler-&gt;insertLogo( $foto );
*/</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">/* Definição de constantes que poderão ser usadas na chamada ao método insertLogo() */</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_TOP_LEFT'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_TOP_LEFT'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_TOP_RIGHT'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_TOP_RIGHT'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">2</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_TOP_CENTER'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_TOP_CENTER'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">3</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_BOTTOM_LEFT'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_BOTTOM_LEFT'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">4</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_BOTTOM_RIGHT'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_BOTTOM_RIGHT'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">5</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_BOTTOM_CENTER'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_BOTTOM_CENTER'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">6</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_MIDDLE_LEFT'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_MIDDLE_LEFT'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">7</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_MIDDLE_RIGHT'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_MIDDLE_RIGHT'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">8</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_MIDDLE_CENTER'</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'IMGHANDLER_LOGO_MIDDLE_CENTER'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">9</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * A classe \c ImgHandler é responsável por copiar imagens (de um diretório ou de um formulário, por meio de envio por método POST), redimensioná-las e inserir a logomarca (marca d'água).
 * @class ImgHandler
 * @author Roberto Beraldo Chaiben (rbchaiben [at] gmail [dot] com)
 * @version 1.1
 * @see http://www.php.net/manual/pt_BR/book.image.php
 * @see http://www.php.net/manual/pt_BR/features.file-upload.php
*/</span>
<span style="color: #000000; font-weight: bold;">class</span> ImgHandler
<span style="color: #009900;">&#123;</span>
&nbsp;
&nbsp;
	<span style="color: #666666; font-style: italic;">/*=============================================*/</span>
	<span style="color: #666666; font-style: italic;">/*====     PROPRIEDADES DA CLASSE     =========*/</span>
	<span style="color: #666666; font-style: italic;">/*=============================================*/</span>
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Largura máxima das imagens, em pixels.
	 * @private max_img_width
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$max_img_width</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">450</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Altura máxima das imagens, em pixels.
	 * @private max_img_height
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$max_img_height</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">450</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Largura máxima das miniaturas (\em thumbnails), em pixels.
	 * @private max_thumb_width
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$max_thumb_width</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">110</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Altura máxima das miniaturas (\em thumbnails), em pixels.
	 * @private max_thumb_height
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$max_thumb_height</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">110</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Prefixo que diferencia uma miniatura (\em thumbnail) de sua imagem original.
	 * @private thumb_prefix
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$thumb_prefix</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Sufixo que diferencia uma miniatura (\em thumbnail) de sua imagem original.
	 * @private thumb_sufix
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$thumb_sufix</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'_thumb'</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Qualidade final da imagem (inteiro entre 0 e 100).
	 * @note Esse valor só é usado em imagens JPEG.
	 * @private img_quality
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$img_quality</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">80</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Qualidade final da miniatura (\e thumbnail) (inteiro entre 0 e 100).
	 * @note Esse valor só é usado em imagens JPEG.
	 * @private thumb_quality
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$thumb_quality</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">70</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Caminho para o arquivo da logomarca (marca d'água) que deve ser inserida nas imagens.
	 * @private logo_file
	*/</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$logo_file</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'logo.png'</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #666666; font-style: italic;">/*==============================================*/</span>
	<span style="color: #666666; font-style: italic;">/*=========     MÉTODOS DA CLASSE     ==========*/</span>
	<span style="color: #666666; font-style: italic;">/*==============================================*/</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Salva a imagem, redimensionando-a, se ultrapassar as dimensões máximas permitidas.
	 * @param filename Caminho para a imagem que deve ser salva.
	 * @return Retorna o nome da imagem salva.
	 * @note O nome final do arquivo da iamgem é gerado dinamicamente, a fim de evitar arquivos com nomes iguais e, consequentemente, sobreescrita de arquivos diferentes.
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> saveImg<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #990000;">list</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$altura</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// se as dimensões da imagem forem maiores que as permitidas, faz o redimensionamento dela.</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$largura</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_img_width</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$altura</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_img_height</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ResizeImg</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// gera um nome para a imagem.</span>
		<span style="color: #000088;">$novo_nome</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">randName</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #990000;">copy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span><span style="color: #339933;">,</span> <span style="color: #000088;">$novo_nome</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$novo_nome</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*---------------------------------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Redimensiona uma imagem e a salva.
	 * @param filename Imagem a ser redimensionada.
	 * @return Retorna o nome da imagem salva.
	*/</span>
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">function</span> ResizeImg<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #990000;">list</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$altura</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$img_type</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getImgType</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// define largura e altura conforma o tamanho da imagem,</span>
		<span style="color: #666666; font-style: italic;">// a fim de manter a proporção entre as dimensões</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$largura</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$altura</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$nova_largura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_img_width</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$nova_altura</span> <span style="color: #339933;">=</span> <span style="color: #990000;">round</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$nova_largura</span> <span style="color: #339933;">/</span> <span style="color: #000088;">$largura</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #000088;">$altura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$altura</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$largura</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$nova_altura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_img_height</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$nova_largura</span> <span style="color: #339933;">=</span> <span style="color: #990000;">round</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$nova_altura</span> <span style="color: #339933;">/</span> <span style="color: #000088;">$altura</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #000088;">$largura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$nova_altura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$nova_largura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_img_width</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$src_img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">call_user_func</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'imagecreatefrom'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$img_type</span><span style="color: #339933;">,</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$dst_img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">imagecreatetruecolor</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$nova_largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nova_altura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
		<span style="color: #990000;">imagecopyresampled</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dst_img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$src_img</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nova_largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nova_altura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$altura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000088;">$nome_img</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">randName</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// verifica se é JPEG</span>
		<span style="color: #666666; font-style: italic;">// Se for, adiciona o terceiro parâmetro (img_quality)</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_type</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">'jpeg'</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #990000;">imagejpeg</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dst_img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nome_img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">img_quality</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #990000;">call_user_func</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'image'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$img_type</span><span style="color: #339933;">,</span> <span style="color: #000088;">$dst_img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nome_img</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
		<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$src_img</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dst_img</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$nome_img</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*------------------------------------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Gera \em thumbnail de uma imagem.
	 * @param filename Imagem da qual deve ser gerado o \em thumbnail.
	 * @return Retorna o nome final do \em thumbnail.
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> createThumb<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #990000;">list</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$altura</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$img_type</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getImgType</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// define largura e altura conforma o tamanho da imagem,</span>
		<span style="color: #666666; font-style: italic;">// a fim de manter a proporção entre as dimensões</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$largura</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$altura</span><span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$nova_largura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_thumb_width</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$nova_altura</span> <span style="color: #339933;">=</span> <span style="color: #990000;">round</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$nova_largura</span> <span style="color: #339933;">/</span> <span style="color: #000088;">$largura</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #000088;">$altura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$altura</span> <span style="color: #339933;">&gt;</span> <span style="color: #000088;">$largura</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$nova_altura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_thumb_height</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$nova_largura</span> <span style="color: #339933;">=</span> <span style="color: #990000;">round</span><span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$nova_altura</span> <span style="color: #339933;">/</span> <span style="color: #000088;">$altura</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #000088;">$largura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$nova_altura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$nova_largura</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_thumb_width</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$src_img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">call_user_func</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'imagecreatefrom'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$img_type</span><span style="color: #339933;">,</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$dst_img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">imagecreatetruecolor</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$nova_largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nova_altura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
&nbsp;
		<span style="color: #990000;">imagecopyresampled</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dst_img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$src_img</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nova_largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nova_altura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$largura</span><span style="color: #339933;">,</span> <span style="color: #000088;">$altura</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000088;">$ext</span> <span style="color: #339933;">=</span> <span style="color: #990000;">end</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">explode</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'.'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$nome_arr</span> <span style="color: #339933;">=</span> <span style="color: #990000;">pathinfo</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$nome_img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">dirname</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #009900; font-weight: bold;">DIRECTORY_SEPARATOR</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">thumb_prefix</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$nome_arr</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'filename'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">thumb_sufix</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'.'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$ext</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// verifica se é JPEG</span>
		<span style="color: #666666; font-style: italic;">// Se for, adiciona o terceiro parâmetro (thumb_quality)</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_type</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">'jpeg'</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #990000;">imagejpeg</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dst_img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nome_img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">thumb_quality</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #990000;">call_user_func</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'image'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$img_type</span><span style="color: #339933;">,</span> <span style="color: #000088;">$dst_img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$nome_img</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$src_img</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$dst_img</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$nome_img</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*----------------------------------------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Gera um novo nome para a imagem, evitando que haja arquivos com os mesmos nomes.
	 * @param filename Nome original do arquivo.
	 * @return Retorna o novo nome do arquivo.
	 * @note Se for passado um caminho completo para o método (com nomes de diretórios), o retorno conterá o caminho completo também, alterando apenas o nome do arquivo, sem modificar os nomes dos diretórios.
	*/</span>
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">function</span> randName<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$tipo</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$tipo</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$tipo</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$tipo</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">case</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span>
				<span style="color: #000088;">$ext</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'gif'</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">case</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">:</span>
				<span style="color: #000088;">$ext</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'jpg'</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">case</span> <span style="color: #cc66cc;">3</span><span style="color: #339933;">:</span>
				<span style="color: #000088;">$ext</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'png'</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
				<span style="color: #000088;">$ext</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span><span style="color: #000088;">$ext</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$novo_nome</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strtolower</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;.&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #990000;">uniqid</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">time</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$nome</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$novo_nome</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;.&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$ext</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">dirname</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #009900; font-weight: bold;">DIRECTORY_SEPARATOR</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$nome</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*---------------------------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Insere logomarca (marca d'água) numa imagem.
	 * @param filename Caminho para o arquivo da imagem na qual deve ser inserida a logomarca (marca d'água).
	 * @param logoBorder Distância que a logomarca (marca d'água) ficará da borda da imagem, em pixels. Por padrão, essa distância é de 5 pixels.
	 * @param logoPosition Posição em que deverá ser inserida a logomarca (marca d'água). Pode ser um dos seguintes valores (constantes):
	 * 	@li IMGHANDLER_LOGO_TOP_LEFT -&gt; Insere no topo esquerdo;
	 * 	@li IMGHANDLER_LOGO_TOP_RIGHT -&gt; Insere no topo direito;
	 * 	@li IMGHANDLER_LOGO_TOP_CENTER -&gt; Insere no topo central;
	 * 	@li IMGHANDLER_LOGO_BOTTOM_LEFT -&gt; Insere na base esquerda;
	 * 	@li IMGHANDLER_LOGO_BOTTOM_RIGHT -&gt; Insere na base direita;
	 * 	@li IMGHANDLER_LOGO_BOTTOM_CENTER -&gt; Insere na base central;
	 * 	@li IMGHANDLER_LOGO_MIDDLE_LEFT -&gt; Insere na pate central vertical, à esquerda;
	 * 	@li IMGHANDLER_LOGO_MIDDLE_RIGHT -&gt; Insere na pate central vertical, à direita;
	 * 	@li IMGHANDLER_LOGO_MIDDLE_CENTER -&gt; Insere na pate central vertical, centrailzado horizontalmente;
	 *
	 *
	 * Por padrão, a logomarca é inserida na base direita.
	 *
	 * @return Retorna TRUE em caso de sucesso e FALSE em caso de erro.
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> insertLogo<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span><span style="color: #339933;">,</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">,</span> <span style="color: #000088;">$logoPosition</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">NULL</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span><span style="color: #990000;">file_exists</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Arquivo <span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$filename</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span> não encontrado&quot;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span><span style="color: #990000;">is_int</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$logoBorder</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logoPosition</span> <span style="color: #339933;">==</span> <span style="color: #009900; font-weight: bold;">NULL</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">// assume o valor padrão</span>
			<span style="color: #000088;">$logoPosition</span> <span style="color: #339933;">=</span> IMGHANDLER_LOGO_BOTTOM_RIGHT<span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$logoBorder</span><span style="color: #339933;">++;</span>
&nbsp;
		<span style="color: #000088;">$logo_type</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getImgType</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">logo_file</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$img_type</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getImgType</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span><span style="color: #000088;">$logo_type</span> <span style="color: #339933;">||</span> <span style="color: #339933;">!</span><span style="color: #000088;">$img_type</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">call_user_func</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'imagecreatefrom'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$img_type</span><span style="color: #339933;">,</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$logo</span> <span style="color: #339933;">=</span> <span style="color: #990000;">call_user_func</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'imagecreatefrom'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$logo_type</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">logo_file</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// dimensões das imagens</span>
		<span style="color: #000088;">$img_size</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">imagesx</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">imagesy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$logo_size</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">imagesx</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">imagesy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// ponto onde deverá ser inserida a logomarca</span>
		<span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logoPosition</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_TOP_LEFT<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_TOP_RIGHT<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_TOP_CENTER<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_BOTTOM_LEFT<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_BOTTOM_RIGHT<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_BOTTOM_CENTER<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_MIDDLE_LEFT<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_MIDDLE_RIGHT<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$logoBorder</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">case</span> IMGHANDLER_LOGO_MIDDLE_CENTER<span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #339933;">-</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$logoBorder</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
				<span style="color: #000088;">$x</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$y</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span><span style="color: #000088;">$x</span> <span style="color: #339933;">||</span> <span style="color: #339933;">!</span><span style="color: #000088;">$y</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$logo_point</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$x</span><span style="color: #339933;">,</span> <span style="color: #000088;">$y</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #990000;">imagecopy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$logo</span><span style="color: #339933;">,</span> <span style="color: #000088;">$logo_point</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$logo_point</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$logo_size</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #666666; font-style: italic;">// verifica se é JPEG</span>
		<span style="color: #666666; font-style: italic;">// Se for, adiciona o terceiro parâmetro (thumb_quality)</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_type</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">'jpeg'</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #990000;">imagejpeg</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$filename</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">img_quality</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #990000;">call_user_func</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'image'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$img_type</span><span style="color: #339933;">,</span> <span style="color: #000088;">$img</span><span style="color: #339933;">,</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
		<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #990000;">imagedestroy</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*----------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Identifica o tipo de uma imagem.
	 * @param filename Caminho da imagem.
	 * @return Retorna o tipo da imagem (gif, jpeg ou png). 
	*/</span>
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">function</span> getImgType<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$type</span> <span style="color: #339933;">=</span> <span style="color: #990000;">getimagesize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$filename</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$type</span> <span style="color: #339933;">==</span> <span style="color: #009900; font-weight: bold;">FALSE</span> <span style="color: #339933;">||</span> <span style="color: #339933;">!</span><span style="color: #990000;">is_array</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$type</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$type</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">case</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">:</span> <span style="color: #666666; font-style: italic;">// GIF</span>
				<span style="color: #000088;">$img_type</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'gif'</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">case</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">:</span> <span style="color: #666666; font-style: italic;">// JPEG</span>
				<span style="color: #000088;">$img_type</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'jpeg'</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">case</span> <span style="color: #cc66cc;">3</span><span style="color: #339933;">:</span> <span style="color: #666666; font-style: italic;">// PNG</span>
				<span style="color: #000088;">$img_type</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'png'</span><span style="color: #339933;">;</span>
				<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
				<span style="color: #000088;">$img_type</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$img_type</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*-----------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Modifica as dimensões máximas das iamgens.
	 * @param width Largura máxima das imagens.
	 * @param height Altgura máxima das imagens.
&nbsp;
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setMaxImgSize<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$width</span><span style="color: #339933;">,</span> <span style="color: #000088;">$height</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #990000;">is_integer</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$width</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #990000;">is_integer</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$height</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_img_width</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$width</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_img_height</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$height</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Modifica as dimensões máximas das miniaturas (thumbnails).
	 * @param width Largura máxima das miniaturas (thumbnails).
	 * @param height Altgura máxima das miniaturas (thumbnails).
&nbsp;
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setMaxThumbSize<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$width</span><span style="color: #339933;">,</span> <span style="color: #000088;">$height</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #990000;">is_integer</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$width</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #990000;">is_integer</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$height</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_thumb_width</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$width</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">max_thumb_height</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$height</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Determina o prefixo das miniaturas (thumbnails)
	 * @param prefix Prefixo das miniaturas (thumbnails)
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setThumbPrefix<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$prefix</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">thumb_prefix</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$prefix</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*----------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Determina o sufixo das miniaturas (thumbnails)
	 * @param sufix Sufixo das miniaturas (thumbnails)
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setThumbSufix<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$sufix</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">thumb_sufix</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$sufix</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*----------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Define a qualidade final da imagem.
	 * @note Esse valor só é usado em imagens JPEG.
	 * @param img_quality Qualidade final da imagem. Deve ser um inteiro entre 0 e 100.
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setImgQuality<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_quality</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span><span style="color: #990000;">is_int</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$img_quality</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$img_quality</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$img_quality</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">100</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">img_quality</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$img_quality</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*-------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Define a qualidade final da miniatura (\e thumbnail).
	 * @note Esse valor só é usado em imagens JPEG.
	 * @param thumb_quality Qualidade final da miniatura (\e thumbnail). Deve ser um inteiro entre 0 e 100.
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setThumbQuality<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$thumb_quality</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span><span style="color: #990000;">is_int</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$thumb_quality</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$thumb_quality</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">0</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$thumb_quality</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">100</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
&nbsp;
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">thumb_quality</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$thumb_quality</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*-------------------------*/</span>
&nbsp;
&nbsp;
&nbsp;
&nbsp;
	<span style="color: #009933; font-style: italic;">/**
	 * Altera o caminho do arquivo da logomarca (marca d'água) que deve sr inserida nas imagens.
	 * @param logo_file Caminho para o arquivo da logomarca (marca d'água).
	*/</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setLogoFile<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_file</span> <span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #339933;">!</span><span style="color: #990000;">file_exists</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$logo_file</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Arquivo <span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$logo_file</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span> não encontrado. Retornando ao valor padrão.&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">else</span>
		<span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">logo_file</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logo_file</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #666666; font-style: italic;">/*---------------------*/</span>
&nbsp;
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>O exemplo de uso está no começo do arquivo, na forma de comentário.</p>
<p>As tags da documentação são direcionadas ao <a href="http://www.stack.nl/~dimitri/doxygen" target="_blank" onclick="urchinTracker('/outgoing/www.stack.nl/_dimitri/doxygen?referer=');">Doxygen</a>, que possui muito mais opções que o PhpDoc. Por isso há umas tags não existentes no PhpDoc.</p>
<p>Gerei a documentação em HTML e em PDF para exemplificar.<br />O arquivo ZIP abaixo possui o código-fonte e as documentações completas:</p>
<p><a href="http://www.inf.ufpr.br/rbc08/src/phpClassImgHandler.zip" onclick="urchinTracker('/outgoing/www.inf.ufpr.br/rbc08/src/phpClassImgHandler.zip?referer=');">http://www.inf.ufpr.br/rbc08/src/phpClassImgHandler.zip</a></p>
<p>Façam bom uso da classe e mantenham os créditos, por favor.</p>
<p>Abraços,</p>
<p>Beraldo</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/classe-php-para-manipulacao-de-imagens/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Recursos Interessantes do Smarty</title>
		<link>http://www.rberaldo.com.br/blog/recursos-interessantes-do-smarty/</link>
		<comments>http://www.rberaldo.com.br/blog/recursos-interessantes-do-smarty/#comments</comments>
		<pubDate>Fri, 15 May 2009 19:58:00 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[gerenciador de templates]]></category>
		<category><![CDATA[smarty]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/2009/05/15/recursos-interessantes-do-smarty/</guid>
		<description><![CDATA[O Smarty é um dos principais gerenciadores de templates para o PHP. Neste artigo são mostrados alguns recursos interessantes dessa ferramenta.]]></description>
			<content:encoded><![CDATA[<p>Hoje falarei sobre alguns recursos interessantes do gerenciador de templates Smarty (<a href="http://www.smarty.net" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net?referer=');">http://www.smarty.net</a>).</p>
<p>Assumo que o leitor já conhece a sintaxe básica do Smarty, como rodar um template, qual estrutura de diretórios utilizar e como alterar o include_path para facilitar as configurações do gerenciador. Se não souber, veja esta seção: <a href="http://www.smarty.net/manual/pt_BR/installation.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/installation.php?referer=');">http://www.smarty.net/manual/pt_BR/installation.php</a></p>
<p><span id="more-17"></span></p>
<p><a href="#dateformat">1. Formatação de Datas</a><br />
<a href="#defaultvalues">2. Definindo Valores Padrões</a><br />
<a href="#numberformat">3. Formatando Números</a><br />
<a href="#truncatetext">4. Truncando Textos</a><br />
<a href="#savetext">5. Salvando textos em Variáveis</a><br />
<a href="#loops">6. Loops (Estruturas de Repetição)</a><br />
<a href="#counters">7. Contadores</a><br />
<a href="#altvalues">8. Alternando Valores em um Loop</a><br />
<a href="#popform">9. Populando Elemenos de Formulários</a><br />
<a href="#tables">10. Gerando Tabelas HTML</a><br />
<a href="#hideemail">11. Escondendo dos Bots de Spam Endereços de E-Mail</a></p>
<h3><a name="dateformat">1. Formatação de Datas</a></h3>
<p>O Smarty possui um modificador de variável chamado <strong>date_format</strong>. Ele se assemelha à função <strong>strftime()</strong>, do PHP. </p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'data'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'2009-05-15'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #000088;">$data</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$data</span><span style="color: #339933;">|</span>date_format<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$data</span><span style="color: #339933;">|</span>date_format<span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%d</span>/%m/%Y&quot;</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Saída:</p>
<pre style="border: dotted 1px #666">
2009-05-15
May 15, 2009
15/05/2009
</pre>
<p>Veja mais detalhes e todos os especificadores de formatação em <a href="http://www.smarty.net/manual/pt_BR/language.modifier.date.format.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.modifier.date.format.php?referer=');">http://www.smarty.net/manual/pt_BR/language.modifier.date.format.php</a></p>
<h3><a name="defaultvalues">2. Definindo Valores Padrões</a></h3>
<p>Para verificar se um valor é diferente de NULL (vazio), costuma-se fazer uma condicional (if). Por exemplko:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>img src<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;{if <span style="color: #006699; font-weight: bold;">$foto</span> != ''}<span style="color: #006699; font-weight: bold;">{$foto}</span>{else}semfoto.gif{/if}&quot;</span> <span style="color: #339933;">/&gt;</span></pre></td></tr></table></div>

<p>Porém, isto pode ser simplificado para:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>img src<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;{<span style="color: #006699; font-weight: bold;">$foto</span>|default:&quot;</span>semfoto<span style="color: #339933;">.</span>gif<span style="color: #0000ff;">&quot;}&quot;</span> <span style="color: #339933;">/&gt;</span></pre></td></tr></table></div>

<p>Mais informações: <a href="http://www.smarty.net/manual/pt_BR/language.modifier.default.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.modifier.default.php?referer=');">http://www.smarty.net/manual/pt_BR/language.modifier.default.php</a></p>
<h3><a name="numberformat">3. Formatando Números</a></h3>
<p>Podemos usar <strong>string_format</strong> para formatar um número, usando as mesmas regras da função <strong>printf()</strong>.</p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'numero'</span><span style="color: #339933;">,</span> <span style="color:#800080;">42.757428942</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #000088;">$numero</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$numero</span><span style="color: #339933;">|</span>string_format<span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%.2f</span>&quot;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$numero</span><span style="color: #339933;">|</span>string_format<span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%07.3f</span>&quot;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$numero</span><span style="color: #339933;">|</span>string_format<span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%d</span>&quot;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$numero</span><span style="color: #339933;">|</span>string_format<span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%05d</span>&quot;</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Saída:</p>
<pre style="border: dotted 1px #666">
42.757428942
42.76
042.757
42
00042
</pre>
<p>Mais detalhes: <a href="http://www.smarty.net/manual/pt_BR/language.modifier.string.format.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.modifier.string.format.php?referer=');">http://www.smarty.net/manual/pt_BR/language.modifier.string.format.php</a></p>
<h3><a name="truncatetext">4. Truncando Textos</a></h3>
<p>Muitas vezes deseja-se truncar um texto para uma certa quantidade de caracteres ou palavras. Geralmente usa-se <strong>substr()</strong>. O inconveniente dessa função é que ela corta palavras. Há como contornar isso somente com PHP, mas o Smarty facilita ainda mais nesse caso.</p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'texto'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi in enim est. Nam placerat adipiscing pretium. Sed at est odio. Vestibulum metus sapien, tincidunt et viverra eget, bibendum molestie justo.'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #000088;">$texto</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">|</span>truncate<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">|</span>truncate<span style="color: #339933;">:</span><span style="color: #cc66cc;">87</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">|</span>truncate<span style="color: #339933;">:</span><span style="color: #cc66cc;">87</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;(continua)&quot;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">|</span>truncate<span style="color: #339933;">:</span><span style="color: #cc66cc;">87</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;...&quot;</span><span style="color: #339933;">:</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Saída:</p>
<pre style="border: dotted 1px #666">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi in enim est. Nam placerat adipiscing pretium. Sed at est odio. Vestibulum metus sapien, tincidunt et viverra eget, bibendum molestie justo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi in enim est....
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi in enim est. Nam...
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi in enim est.(continua)
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi in enim est. Nam plac...
</pre>
<p>Mais informações <a href="http://www.smarty.net/manual/pt_BR/language.modifier.truncate.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.modifier.truncate.php?referer=');">http://www.smarty.net/manual/pt_BR/language.modifier.truncate.php</a></p>
<h3><a name="savetext">5. Salvando textos em Variáveis</a></h3>
<p>É possível salvar um texto gerado pelo Smarty em uma variável. Uma aplicação para isso é numa paginação, por exemplo, onde a barra com os números das páginas é exibida mais de uma vez.</p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'paginas'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">3</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">4</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">6</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>capture name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;barra_pag&quot;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #b1b100;">foreach</span> from<span style="color: #339933;">=</span><span style="color: #000088;">$paginas</span> item<span style="color: #339933;">=</span>i<span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#123;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#125;</span> 
<span style="color: #009900;">&#123;</span><span style="color: #339933;">/</span><span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #339933;">/</span>capture<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$smarty</span><span style="color: #339933;">.</span>capture<span style="color: #339933;">.</span>barra_pag<span style="color: #009900;">&#125;</span>
&nbsp;
conteú<span style="color: #b1b100;">do</span> da página
&nbsp;
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$smarty</span><span style="color: #339933;">.</span>capture<span style="color: #339933;">.</span>barra_pag<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Saída:</p>
<pre style="border: dotted 1px #666">
1 2 3 4 5 6

conteúdo da página

1 2 3 4 5 6
</pre>
<h3><a name="loops">6. Loops (Estruturas de Repetição)</a></h3>
<p>As duas estruturas de repetição do Smarty são <strong>foreach</strong> e <strong>section</strong>. A principal diferença entra as duas é que <strong>section</strong> permite modificar o incremento do contador, como num loop <strong>while</strong>.</p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'array'</span><span style="color: #339933;">,</span> <span style="color: #990000;">range</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">20</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #b1b100;">foreach</span> from<span style="color: #339933;">=</span><span style="color: #000088;">$array</span> item<span style="color: #339933;">=</span>i <span style="color: #990000;">key</span><span style="color: #339933;">=</span>k<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$k</span><span style="color: #009900;">&#125;</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900;">&#123;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #339933;">/</span><span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #009900;">&#123;</span>section name<span style="color: #339933;">=</span>cont loop<span style="color: #339933;">=</span><span style="color: #000088;">$array</span> step<span style="color: #339933;">=</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$array</span><span style="color: #009900;">&#91;</span>cont<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #339933;">/</span>section<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>section name<span style="color: #339933;">=</span>cont loop<span style="color: #339933;">=</span><span style="color: #000088;">$array</span> step<span style="color: #339933;">=</span><span style="color: #cc66cc;">2</span> start<span style="color: #339933;">=</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #000088;">$array</span><span style="color: #009900;">&#91;</span>cont<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span><span style="color: #339933;">/</span>section<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Saída:</p>
<div class="codeBox">
<pre style="border: dotted 1px #666">
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
5 => 6
6 => 7
7 => 8
8 => 9
9 => 10
10 => 11
11 => 12
12 => 13
13 => 14
14 => 15
15 => 16
16 => 17
17 => 18
18 => 19
19 => 20

1
3
5
7
9
11
13
15
17
19

6
8
10
12
14
16
18
20
</pre>
</div>
<p>Mais informações:<br />
<a href="http://www.smarty.net/manual/pt_BR/language.function.section.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.function.section.php?referer=');">http://www.smarty.net/manual/pt_BR/language.function.section.php</a><br />
<a href="http://www.smarty.net/manual/pt_BR/language.function.foreach.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.function.foreach.php?referer=');">http://www.smarty.net/manual/pt_BR/language.function.foreach.php</a></p>
<h3><a name="counters">7. Contadores</a></h3>
<p>O Smarty tem um recurso próprio para usar contadores dentro de templates. É o <strong>counter</strong>.</p>
<p>Este exemplo não requer a exibição do script PHP. Basta dar um display() no tenplate, não sendo necessário atribuir valor a variáveis de templates.</p>
<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>counter start<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span> skip<span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>counter start<span style="color: #339933;">=</span><span style="color: #cc66cc;">7</span> skip<span style="color: #339933;">=</span><span style="color: #cc66cc;">4</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#123;</span>counter start<span style="color: #339933;">=</span><span style="color: #cc66cc;">77</span> skip<span style="color: #339933;">=</span><span style="color: #cc66cc;">7</span> direction<span style="color: #339933;">=</span>down<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>counter<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Saída:</p>
<pre style="border: dotted 1px #666">
0
1
2

7
11
15
19

77
70
63
56
49
</pre>
<h3><a name="altvalues">8. Alternando Valores em um Loop</a></h3>
<p>Uma dúvida muito frequente em fóruns é como alternar cores de linhas de tabelas. Há diversas formas de solucionar esse problema apenas com PHP, mas, novamentem o Smarty facilita o trabalho. Usaremos a função <strong>cycle</strong>.</p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'array'</span><span style="color: #339933;">,</span> <span style="color: #990000;">range</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>table border<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;1&quot;</span> width<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;40&quot;</span> cellpadding<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;2&quot;</span> cellspacing<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;1&quot;</span><span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span><span style="color: #b1b100;">foreach</span> from<span style="color: #339933;">=</span><span style="color: #000088;">$array</span> item<span style="color: #339933;">=</span>i<span style="color: #009900;">&#125;</span>
  <span style="color: #339933;">&lt;</span>tr style<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;background: {cycle values=&quot;</span><span style="color: #666666; font-style: italic;">#ccc,#666&quot;}&quot;&gt;
</span>    <span style="color: #339933;">&lt;</span>td<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#123;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">&lt;/</span>td<span style="color: #339933;">&gt;</span>
  <span style="color: #339933;">&lt;/</span>tr<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span><span style="color: #339933;">/</span><span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&lt;/</span>table<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Saída:</p>
<pre style="border: dotted 1px #666">
<table border="1" width="40" cellpadding="2" cellspacing="1">
<tr style="background: #ccc">
<td>1</td>
</tr>
<tr style="background: #666">
<td>2</td>
</tr>
<tr style="background: #ccc">
<td>3</td>
</tr>
<tr style="background: #666">
<td>4</td>
</tr>
<tr style="background: #ccc">
<td>5</td>
</tr>
<tr style="background: #666">
<td>6</td>
</tr>
<tr style="background: #ccc">
<td>7</td>
</tr>
<tr style="background: #666">
<td>8</td>
</tr>
<tr style="background: #ccc">
<td>9</td>
</tr>
<tr style="background: #666">
<td>10</td>
</tr>
</table>
</pre>
<h3><a name="popform">9. Populando Elemenos de Formulários</a></h3>
<p>Há três elementos de formulário que geralmente são populados com valores personalizados, geralmente provenientes de bases de dados: <strong><em>checkboxes</em></strong>, <strong><em>radios</em></strong> e <strong><em>options</em></strong>. O Smarty possui funções específicas para esses três elementos.</p>
<p><strong>Populando <em>checkboxes</em></strong></p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'check_id'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'v1'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v2'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v3'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v4'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v5'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'check_value'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'valor 1'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 2'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 3'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 4'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 5'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'check_selected'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v3'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>html_checkboxes name<span style="color: #339933;">=</span>opcoes values<span style="color: #339933;">=</span><span style="color: #000088;">$check_id</span> output<span style="color: #339933;">=</span><span style="color: #000088;">$check_value</span> selected<span style="color: #339933;">=</span><span style="color: #000088;">$check_selected</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><strong>Populando <em>radios</em></strong></p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'radio_id'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'v1'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v2'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v3'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v4'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v5'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'radio_value'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'valor 1'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 2'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 3'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 4'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 5'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'radio_selected'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v3'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>html_radios name<span style="color: #339933;">=</span>opcoes values<span style="color: #339933;">=</span><span style="color: #000088;">$radio_id</span> output<span style="color: #339933;">=</span><span style="color: #000088;">$radio_value</span> checked<span style="color: #339933;">=</span><span style="color: #000088;">$radio_selected</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><strong>Populando <em>options</em></strong></p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'op_id'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'v1'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v2'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v3'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v4'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v5'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'op_value'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'valor 1'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 2'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 3'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 4'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'valor 5'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'op_selected'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'v3'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>select name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;opcoes&quot;</span><span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#123;</span>html_options  values<span style="color: #339933;">=</span><span style="color: #000088;">$op_id</span> output<span style="color: #339933;">=</span><span style="color: #000088;">$op_value</span> selected<span style="color: #339933;">=</span><span style="color: #000088;">$op_selected</span><span style="color: #009900;">&#125;</span>
<span style="color: #339933;">&lt;/</span>select<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Saídas das três funcções:</p>
<div class="codeBox">
<pre style="border: dotted 1px #666">
<label>
<input type="checkbox" name="opcoes[]" value="v1" />valor 1</label>
<label>
<input type="checkbox" name="opcoes[]" value="v2" />valor 2</label>
<label>
<input type="checkbox" name="opcoes[]" value="v3" checked="checked" />valor 3</label>

<label>
<input type="checkbox" name="opcoes[]" value="v4" />valor 4</label>
<label>
<input type="checkbox" name="opcoes[]" value="v5" />valor 5</label>

<label>
<input type="radio" name="opcoes" value="v1" />valor 1</label>
<label>
<input type="radio" name="opcoes" value="v2" />valor 2</label>
<label>
<input type="radio" name="opcoes" value="v3" checked="checked" />valor 3</label>
<label>
<input type="radio" name="opcoes" value="v4" />valor 4</label>
<label>
<input type="radio" name="opcoes" value="v5" />valor 5</label>
<select name="opcoes">
<option label="valor 1" value="v1">valor 1</option>
<option label="valor 2" value="v2">valor 2</option>
<option label="valor 3" value="v3" selected="selected">valor 3</option>
<option label="valor 4" value="v4">valor 4</option>
<option label="valor 5" value="v5">valor 5</option>
</select>
</pre>
</div>
<p>Há dois casos particulares para a criação de <em>options</em>: para data e para hora. O Smarty também tem funções específicas para isso.</p>
<p>Para esse caso, não é necessário definir variáveis no script PHP. Basta dar um display() no template.</p>
<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>html_select_date start_year<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;-100&quot;</span> month_format<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;%m&quot;</span> field_order<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;DMY&quot;</span> field_separator<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;/&quot;</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Saída:</p>
<div class="codeBox">
<pre style="border: dotted 1px #666">
<select name="Date_Day">
<option label="01" value="1">01</option>
<option label="02" value="2">02</option>
<option label="03" value="3">03</option>
<option label="04" value="4">04</option>
<option label="05" value="5">05</option>
<option label="06" value="6">06</option>
<option label="07" value="7">07</option>
<option label="08" value="8">08</option>
<option label="09" value="9">09</option>
<option label="10" value="10">10</option>
<option label="11" value="11">11</option>
<option label="12" value="12">12</option>
<option label="13" value="13">13</option>
<option label="14" value="14">14</option>
<option label="15" value="15" selected="selected">15</option>
<option label="16" value="16">16</option>
<option label="17" value="17">17</option>
<option label="18" value="18">18</option>
<option label="19" value="19">19</option>
<option label="20" value="20">20</option>
<option label="21" value="21">21</option>
<option label="22" value="22">22</option>
<option label="23" value="23">23</option>
<option label="24" value="24">24</option>
<option label="25" value="25">25</option>
<option label="26" value="26">26</option>
<option label="27" value="27">27</option>
<option label="28" value="28">28</option>
<option label="29" value="29">29</option>
<option label="30" value="30">30</option>
<option label="31" value="31">31</option>
</select>

/
<select name="Date_Month">
<option label="01" value="01">01</option>
<option label="02" value="02">02</option>
<option label="03" value="03">03</option>
<option label="04" value="04">04</option>
<option label="05" value="05" selected="selected">05</option>
<option label="06" value="06">06</option>
<option label="07" value="07">07</option>
<option label="08" value="08">08</option>
<option label="09" value="09">09</option>
<option label="10" value="10">10</option>
<option label="11" value="11">11</option>
<option label="12" value="12">12</option>
</select>

/
<select name="Date_Year">
<option label="1909" value="1909">1909</option>
<option label="1910" value="1910">1910</option>
<option label="1911" value="1911">1911</option>
<option label="1912" value="1912">1912</option>
<option label="1913" value="1913">1913</option>
<option label="1914" value="1914">1914</option>
<option label="1915" value="1915">1915</option>
<option label="1916" value="1916">1916</option>
<option label="1917" value="1917">1917</option>
<option label="1918" value="1918">1918</option>
<option label="1919" value="1919">1919</option>
<option label="1920" value="1920">1920</option>
<option label="1921" value="1921">1921</option>
<option label="1922" value="1922">1922</option>
<option label="1923" value="1923">1923</option>
<option label="1924" value="1924">1924</option>
<option label="1925" value="1925">1925</option>
<option label="1926" value="1926">1926</option>
<option label="1927" value="1927">1927</option>
<option label="1928" value="1928">1928</option>
<option label="1929" value="1929">1929</option>
<option label="1930" value="1930">1930</option>
<option label="1931" value="1931">1931</option>
<option label="1932" value="1932">1932</option>
<option label="1933" value="1933">1933</option>
<option label="1934" value="1934">1934</option>
<option label="1935" value="1935">1935</option>
<option label="1936" value="1936">1936</option>
<option label="1937" value="1937">1937</option>
<option label="1938" value="1938">1938</option>
<option label="1939" value="1939">1939</option>
<option label="1940" value="1940">1940</option>
<option label="1941" value="1941">1941</option>
<option label="1942" value="1942">1942</option>
<option label="1943" value="1943">1943</option>
<option label="1944" value="1944">1944</option>
<option label="1945" value="1945">1945</option>
<option label="1946" value="1946">1946</option>
<option label="1947" value="1947">1947</option>
<option label="1948" value="1948">1948</option>
<option label="1949" value="1949">1949</option>
<option label="1950" value="1950">1950</option>
<option label="1951" value="1951">1951</option>
<option label="1952" value="1952">1952</option>
<option label="1953" value="1953">1953</option>
<option label="1954" value="1954">1954</option>
<option label="1955" value="1955">1955</option>
<option label="1956" value="1956">1956</option>
<option label="1957" value="1957">1957</option>
<option label="1958" value="1958">1958</option>
<option label="1959" value="1959">1959</option>
<option label="1960" value="1960">1960</option>
<option label="1961" value="1961">1961</option>
<option label="1962" value="1962">1962</option>
<option label="1963" value="1963">1963</option>
<option label="1964" value="1964">1964</option>
<option label="1965" value="1965">1965</option>
<option label="1966" value="1966">1966</option>
<option label="1967" value="1967">1967</option>
<option label="1968" value="1968">1968</option>
<option label="1969" value="1969">1969</option>
<option label="1970" value="1970">1970</option>
<option label="1971" value="1971">1971</option>
<option label="1972" value="1972">1972</option>
<option label="1973" value="1973">1973</option>
<option label="1974" value="1974">1974</option>
<option label="1975" value="1975">1975</option>
<option label="1976" value="1976">1976</option>
<option label="1977" value="1977">1977</option>
<option label="1978" value="1978">1978</option>
<option label="1979" value="1979">1979</option>
<option label="1980" value="1980">1980</option>
<option label="1981" value="1981">1981</option>
<option label="1982" value="1982">1982</option>
<option label="1983" value="1983">1983</option>
<option label="1984" value="1984">1984</option>
<option label="1985" value="1985">1985</option>
<option label="1986" value="1986">1986</option>
<option label="1987" value="1987">1987</option>
<option label="1988" value="1988">1988</option>
<option label="1989" value="1989">1989</option>
<option label="1990" value="1990">1990</option>
<option label="1991" value="1991">1991</option>
<option label="1992" value="1992">1992</option>
<option label="1993" value="1993">1993</option>
<option label="1994" value="1994">1994</option>
<option label="1995" value="1995">1995</option>
<option label="1996" value="1996">1996</option>
<option label="1997" value="1997">1997</option>
<option label="1998" value="1998">1998</option>
<option label="1999" value="1999">1999</option>
<option label="2000" value="2000">2000</option>
<option label="2001" value="2001">2001</option>
<option label="2002" value="2002">2002</option>
<option label="2003" value="2003">2003</option>
<option label="2004" value="2004">2004</option>
<option label="2005" value="2005">2005</option>
<option label="2006" value="2006">2006</option>
<option label="2007" value="2007">2007</option>
<option label="2008" value="2008">2008</option>
<option label="2009" value="2009" selected="selected">2009</option>
</select>
</pre>
</div>
<p><strong>html_select_time</strong> fica para vocês. =P</p>
<p>Mais informações:<br />
<a href="http://www.smarty.net/manual/pt_BR/language.function.html.checkboxes.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.function.html.checkboxes.php?referer=');">http://www.smarty.net/manual/pt_BR/language.function.html.checkboxes.php</a><br />
<a href="http://www.smarty.net/manual/pt_BR/language.function.html.radios.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.function.html.radios.php?referer=');">http://www.smarty.net/manual/pt_BR/language.function.html.radios.php</a><br />
<a href="http://www.smarty.net/manual/pt_BR/language.function.html.options.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.function.html.options.php?referer=');">http://www.smarty.net/manual/pt_BR/language.function.html.options.php</a><br />
<a href="http://www.smarty.net/manual/pt_BR/language.function.html.select.date.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.function.html.select.date.php?referer=');">http://www.smarty.net/manual/pt_BR/language.function.html.select.date.php</a><br />
<a href="http://www.smarty.net/manual/pt_BR/language.function.html.select.time.php" target="_blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.function.html.select.time.php?referer=');">http://www.smarty.net/manual/pt_BR/language.function.html.select.time.php</a></p>
<h3><a name="tables">10. Gerando Tabelas HTML</a></h3>
<p>É possível gerar tabelas HTML a partir de arrays usando <strong>html_table</strong>.</p>
<p>index.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$Smarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'info'</span><span style="color: #339933;">,</span> <span style="color: #990000;">range</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">30</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>html_table loop<span style="color: #339933;">=</span><span style="color: #000088;">$info</span> cols<span style="color: #339933;">=</span><span style="color: #cc66cc;">5</span> table_attr<span style="color: #339933;">=</span><span style="color: #0000ff;">'border=&quot;2&quot;'</span> tr_attr<span style="color: #339933;">=</span><span style="color: #0000ff;">'style=&quot;background: #ccc&quot;'</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Mais informações:<br />
<a href="http://www.smarty.net/manual/pt_BR/language.function.html.table.php" target=_"blank" onclick="urchinTracker('/outgoing/www.smarty.net/manual/pt_BR/language.function.html.table.php?referer=');">http://www.smarty.net/manual/pt_BR/language.function.html.table.php</a></p>
<h3><a name="hideemail">11. Escondendo dos Bots de Spam Endereços de E-Mail</a></h3>
<p>Colocar endereços de e-mail em páginas HTML acarreta uma grande dor de cabeça: os bots de spam logo aparecem para indexar o e-mail em suas listas de destinatários. Uma boa maneira de esconder dos bots os endereços é codificando-os em hexadecimal, por exemplo, ou em JavaScript. O Smarty possui a função <strong>mailto</strong>.</p>
<p>index.tpl</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>mailto address<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;email@site.com&quot;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#123;</span>mailto address<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;email@site.com&quot;</span> encode<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;hex&quot;</span><span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Saída:</p>
<pre>
<a href="mailto:email@site.com" >email@site.com</a>
<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%65%6d%61%69%6c@%73%69%74%65.%63%6f%6d" >&#x65;&#x6d;&#x61;&#x69;&#x6c;&#x40;&#x73;&#x69;&#x74;&#x65;&#x2e;&#x63;&#x6f;&#x6d;</a>
</pre>
<p>Descobri esse recurso recentemente. Até então eu usava um programa em C que convertia um caractere em hexadecimal. Tinha que fazer isso para cada e-mail que colocasse no site. Agora não preciso mais. =D</p>
<p>Espero que o material seja útil. </p>
<p>Abraços!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/recursos-interessantes-do-smarty/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Limitando o número de links em uma paginação</title>
		<link>http://www.rberaldo.com.br/blog/limitando-o-numero-de-links-em-uma-paginacao/</link>
		<comments>http://www.rberaldo.com.br/blog/limitando-o-numero-de-links-em-uma-paginacao/#comments</comments>
		<pubDate>Thu, 07 May 2009 12:45:00 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Paginação]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/2009/05/07/limitando-o-numero-de-links-em-uma-paginacao/</guid>
		<description><![CDATA[Sistemas de paginação são muito usados. Pretendo mostrar como criar os links para cada página, semelhantemente à maneira usada pelo Google, em que aparecem somente alguns links, para evitar que se mostre uma linha muito extensa.]]></description>
			<content:encoded><![CDATA[<p>Sistemas de paginação são muito usados. Já existem muitos exemplos por aí, tanto em formato de artigos/tutoriais, quanto scripts prontos. Por isso, hoje não vou me ater nas técnicas de realização desse processo. Pretendo mostrar como criar os links para cada página, semelhantemente à maneira usada pelo Google, em que aparecem somente alguns links, para evitar que se mostre uma linha muito extensa.</p>
<p><span id="more-16"></span><br />
Estou considerando que o leitor já sabe como fazer paginação. Se não sabe, é bom ler artigos sobre isso antes de continuar com este tutorial. =P</p>
<p>Usarei variáveis com valores  estátiocs, somente para mostrar a lógica da coisa. Claro que você usará os valores gerados pelo seu sistema de paginação.</p>
<p>A variável &#8220;total&#8221; contém o número total de páginas (não de registros) retornadas pela paginação.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// total de páginas</span>
<span style="color: #000088;">$total</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">50</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A variável &#8220;max_links&#8221; armazena o número máximo de links que serão mostrados.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// número máximo de links da paginação</span>
<span style="color: #000088;">$max_links</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A variaável &#8220;pagina&#8221; contém o valor da página corrente. Esse é o valor que virá da URL.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// página corrente</span>
<span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>&#8220;links_laterais&#8221; contém o número de links que serão mostrados, no máximo, antes e depois da página corrente. Esse valor corresponde à metade do valor de &#8220;max_links&#8221;. Usei ceil() para ter certeza de que será gerado um número inteiro. Se você sempre se lembrar de colocar um número par em &#8220;max_links&#8221;, pode retirar a função ceil(), reduzindo o trabalho do processador e o tempo de execução do script.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// calcula quantos links haverá à esquerda e à direita da página corrente</span>
<span style="color: #666666; font-style: italic;">// usa-se ceil() para assegurar que o número será inteiro</span>
<span style="color: #000088;">$links_laterais</span> <span style="color: #339933;">=</span> <span style="color: #990000;">ceil</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$max_links</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Aqui eu crio as variáveis que serão usadas no loop para gerar os links da paginação. É preferível criar essa variáveis em vez de declará-las denrto do loop. Caso contrário $limite seria calculado a cada iteração do laço ($inicio até poderia ser declarada dentro do for, pois só é calculada uma vez).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// variáveis para o loop</span>
<span style="color: #000088;">$inicio</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$pagina</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$links_laterais</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$limite</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$pagina</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$links_laterais</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Agora vem a parte que faz tudo aparecer. Não tem muito o que explicar. Os IF&#8217;s se explicam por si só.<br />
Quando $i possui o valor da página corrente, o link não é gerado (até porque ninguém pretende ir para a página em que está. =P ). É necessário verificar se $i é maior que um e menor que o total de páginas, para que não sejam criados link inexistentes. Usei a página pagincao.php somente para exemplificar; mude-a para o nome do seu script.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$inicio</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;=</span> <span style="color: #000088;">$limite</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$pagina</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot; &lt;strong&gt;&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;/strong&gt; &quot;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">1</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;=</span> <span style="color: #000088;">$total</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot; &lt;a href=<span style="color: #000099; font-weight: bold;">\&quot;</span>paginacao.php?pagina=&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;/a&gt; &quot;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>O script completo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// total de páginas</span>
<span style="color: #000088;">$total</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">50</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// número máximo de links da paginação</span>
<span style="color: #000088;">$max_links</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
<span style="color: #666666; font-style: italic;">// página corrente</span>
<span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">3</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// calcula quantos links haverá à esquerda e à direita da página corrente</span>
<span style="color: #666666; font-style: italic;">// usa-se ceil() para assegurar que o número será inteiro</span>
<span style="color: #000088;">$links_laterais</span> <span style="color: #339933;">=</span> <span style="color: #990000;">ceil</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$max_links</span> <span style="color: #339933;">/</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// variáveis para o loop</span>
<span style="color: #000088;">$inicio</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$pagina</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$links_laterais</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$limite</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$pagina</span> <span style="color: #339933;">+</span> <span style="color: #000088;">$links_laterais</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$inicio</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;=</span> <span style="color: #000088;">$limite</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$pagina</span><span style="color: #009900;">&#41;</span>
 <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot; &lt;strong&gt;&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;/strong&gt; &quot;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
 <span style="color: #b1b100;">else</span>
 <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">1</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;=</span> <span style="color: #000088;">$total</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot; &lt;a href=<span style="color: #000099; font-weight: bold;">\&quot;</span>paginacao.php?pagina=&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span>&gt;&quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;&lt;/a&gt; &quot;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

</div>
<p>Espero que tenha ficado tudo bem claro. É algo simples, mas que, frequentemente aparece como dúvida em fóruns.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/limitando-o-numero-de-links-em-uma-paginacao/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Tutorial AWK</title>
		<link>http://www.rberaldo.com.br/blog/tutorial-awk/</link>
		<comments>http://www.rberaldo.com.br/blog/tutorial-awk/#comments</comments>
		<pubDate>Thu, 07 May 2009 12:27:00 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Shell Script (Bash)]]></category>
		<category><![CDATA[AWK]]></category>
		<category><![CDATA[Bash]]></category>
		<category><![CDATA[Programação Shell]]></category>
		<category><![CDATA[Shell]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/2009/05/07/tutorial-awk/</guid>
		<description><![CDATA[Não sou nenhum expert ou grande conhecedor da linguagem AWK, mas ela é muito útil e me ajudou muito nas provas sobre Shell Script na faculdade. Por isso resolvi escrever este pequeno e introdutório tutorial acerca dessa linguagem. É bom todo usuário Linux saber usá-la. =) AWK é uma linguagem utilizada para processamento de informações [...]]]></description>
			<content:encoded><![CDATA[<p>Não sou nenhum <em>expert</em> ou grande conhecedor da linguagem AWK, mas ela é muito útil e me ajudou muito nas provas sobre Shell Script na faculdade. Por isso resolvi escrever este pequeno e introdutório tutorial acerca dessa linguagem. É bom todo usuário Linux saber usá-la. =)</p>
<p>AWK é uma linguagem utilizada para processamento de informações em texto, como o conteúdo de um arquivo &#8211; principalmente informações em colunas &#8211; ou a saída de outros comandos, como <strong>cat</strong>, <strong>grep</strong> etc.</p>
<p><span id="more-15"></span><br />
A estrutura de um script AWK (pode estar em um arquivo ou ser escrito diretamente na linha de comando &#8211; Shell) é a seguinte:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;">BEGIN<span style="color: #7a0874; font-weight: bold;">&#123;</span>
 Comandos executados ao iniciar o processamento, antes de ler <span style="color: #c20cb9; font-weight: bold;">as</span> linhas <span style="color: #000000; font-weight: bold;">do</span> texto
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">&#91;</span>condicao<span style="color: #7a0874; font-weight: bold;">&#93;</span><span style="color: #7a0874; font-weight: bold;">&#123;</span>
 Comandos a serem executados em todas <span style="color: #c20cb9; font-weight: bold;">as</span> linhas <span style="color: #000000; font-weight: bold;">do</span> texto
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
END<span style="color: #7a0874; font-weight: bold;">&#123;</span>
 Comando final. Executado após o processamento de todas <span style="color: #c20cb9; font-weight: bold;">as</span> linhas
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></td></tr></table></div>

<p>A condição do segudo bloco é opcional. Se não especificada, os respectivos comandos do bloco serão executados em todas as linhas. Caso contrário, serão executados apenas nas linhas que satisfizerem a condição.<br />
A condição pode ser uma expressão regular. Basta colocá-la entre barras:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">/</span>^A<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">&#123;</span>
 Comando...
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></td></tr></table></div>

<p>Se um bloco de comandos estiver vazio, é executado <strong>print $0</strong>, ou seja, imprime a linha corrente.</p>
<p>Algumas variáveis definidas no AWK:</p>
<p>FS -> separador de campos<br />
NR -> número da linhas<br />
NF -> número de campos na linha</p>
<p>Para mais informações:</p>
<p>Manpage do AWK: <a href="http://www.linuxmanpages.com/man1/awk.1.php" target="_blank" onclick="urchinTracker('/outgoing/www.linuxmanpages.com/man1/awk.1.php?referer=');"><strong>$ man awk</strong></a><br />
<a href="http://www.gnu.org/software/gawk/manual/gawk.html" target="_blank" onclick="urchinTracker('/outgoing/www.gnu.org/software/gawk/manual/gawk.html?referer=');">http://www.gnu.org/software/gawk/manual/gawk.html</a><br />
<a href="http://en.wikipedia.org/wiki/Awk" target="_blank" onclick="urchinTracker('/outgoing/en.wikipedia.org/wiki/Awk?referer=');">http://en.wikipedia.org/wiki/Awk</a></p>
<p>Exemplos:</p>
<p>Filtra  as linhas com o padrão especificado. Linhas que terminam com conf</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #000000; font-weight: bold;">/</span>conf$<span style="color: #000000; font-weight: bold;">/</span></pre></td></tr></table></div>

<p>Usando outro separador de campos e imprimindo colunas</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">passwd</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> -F: <span style="color: #ff0000;">'{print $1}'</span></pre></td></tr></table></div>

<p>Usando separador de campos</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span><span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'{print $1 FS $8}'</span></pre></td></tr></table></div>

<p>Numerando linhas</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'{print NR FS$1 FS $8}'</span></pre></td></tr></table></div>

<p>Filtra linhas com padrão especificado e mostra apenas as colunas 1 e 8.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'/conf$/{print $1&quot; &quot;$8}'</span></pre></td></tr></table></div>

<p>Imprime as linhas com mais de 3 campos. Elimina a primeira linha do ls -l (Total)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'NF &gt; 3'</span></pre></td></tr></table></div>

<p>Filtra linhas com arquivos cujos nomes possuem menos de 5 caracteres</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'length($8) &lt; 5'</span></pre></td></tr></table></div>

<p>Imprime linhas pares</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'NR % 2 == 0 {print NR&quot; &quot;$0}'</span></pre></td></tr></table></div>

<p>Substitui strings</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'{sub(/conf$/,&quot;test&quot;); print $0}'</span></pre></td></tr></table></div>

<p>Procura expressão em determinado campo</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">/</span>etc <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'$8 ~ /^[ae]/'</span></pre></td></tr></table></div>

<p>Inserindo strings entre campos</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span><span style="color: #c20cb9; font-weight: bold;">passwd</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> -F: <span style="color: #ff0000;">'{print &quot;Login: &quot; $1}'</span></pre></td></tr></table></div>

<p>Filtra  a saída de <strong>ls -l</strong>, a fim de mostrar o nome do arquivo, suas permissões e seu tamanho (a condição <strong>NR != 1</strong> evita que a linha <strong>Total</strong> seja exibida):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ls</span> <span style="color: #660033;">-l</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'NR != 1{print &quot;Nome: &quot;$8&quot; Perm: &quot;$1&quot; Tamanho: &quot;$5}'</span></pre></td></tr></table></div>

<p>Imprime o comprimento da maior linha</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'{ if (length($0) &gt; max) max = length($0)}; END { print max}'</span>; arquivo</pre></td></tr></table></div>

<p>Imprime as linhas com mais de 42 caracteres</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'length($0) &gt; 42'</span> arquivo</pre></td></tr></table></div>

<p>Exibe o número de linhas do arquivo</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'END { print NR }'</span> arquivo</pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/tutorial-awk/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Combo com as Cidades e Estados do Brasil Usando Ajax</title>
		<link>http://www.rberaldo.com.br/blog/combo-com-as-cidades-e-estados-do-brasil-usando-ajax/</link>
		<comments>http://www.rberaldo.com.br/blog/combo-com-as-cidades-e-estados-do-brasil-usando-ajax/#comments</comments>
		<pubDate>Thu, 07 May 2009 12:07:00 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[Banco de Dados]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[cidades]]></category>
		<category><![CDATA[cidades e estados]]></category>
		<category><![CDATA[estados]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/2009/05/07/combo-com-as-cidades-e-estados-do-brasil-usando-ajax/</guid>
		<description><![CDATA[Combo (select, list, menu) com as cidades e estados do Brasil. Sistema feito usando Ajax.]]></description>
			<content:encoded><![CDATA[<p>Hoje postarei um script pronto.<br />Trata-se do famoso combo cidades/estados, usando Ajax, onde você seleciona o estado e aparecem suas respectivas cidades.</p>
<p><span id="more-14"></span>Muitos dos bancos de dados de cidades que encontrei na Internet não tinham acentuação. Porém, encontrei <a href="http://phpbrasil.com/scripts/script.php/id/2189" target="_blank" onclick="urchinTracker('/outgoing/phpbrasil.com/scripts/script.php/id/2189?referer=');">este script</a>, que satisfez a quase todas as minhas necessidades.</p>
<p>Fiz alguns ajustes no banco de dados, criei o arquivo de instalação e as funções PHP e JavaScript, para o funcionamento correto do sistema.</p>
<p>Desenvolvi para PHP 5, usando a extensão <strong>MySQLi</strong>.</p>
<p>Como o banco de dados é muito grande, não postarei o código.<br />O download pode ser feito aqui:<br /><a href="http://www.scriptbrasil.com.br/download/codigo/7194" target="_blank" onclick="urchinTracker('/outgoing/www.scriptbrasil.com.br/download/codigo/7194?referer=');">Link para download</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/combo-com-as-cidades-e-estados-do-brasil-usando-ajax/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Tratamento de Erros</title>
		<link>http://www.rberaldo.com.br/blog/tratamento-de-erros-2/</link>
		<comments>http://www.rberaldo.com.br/blog/tratamento-de-erros-2/#comments</comments>
		<pubDate>Wed, 06 May 2009 02:10:00 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Boas Práticas]]></category>
		<category><![CDATA[erros]]></category>
		<category><![CDATA[tratamento de erros]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/2009/05/05/tratamento-de-erros-2/</guid>
		<description><![CDATA[Artigo sobre tratamento de erros. O artigo usa a linguagem PHP, mas as técnicas podem ser adaptadas para qualquer outra linguagem.]]></description>
			<content:encoded><![CDATA[<p>Este tutorial também foi postado originalmente no Fórum iMasters, e foi criado por mim juntamente com outros membros do fórum.</p>
<p>Fonte: <a href="http://forum.imasters.uol.com.br/index.php?showtopic=229485" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.uol.com.br/index.php?showtopic=229485&amp;referer=');">http://forum.imasters.uol.com.br/index.php?showtopic=229485</a></p>
<p><span id="more-13"></span></p>
<h3>Sumário</h3>
<p><a href="#o_que"">1. O que é tratamento de erros</a><br />
<a href="#boas">2. Boas maneiras para programar sem erros</a><br />
<a href="#errada">2.1 Programar de maneira errada</a><br />
<a href="#esconder">2.2 Esconder Erros</a><br />
<a href="#falta">2.3 Falta de uma lógica mais apurada e desenvolvida</a><br />
<a href="#usuarios">2.4 Não pensar nos usuários</a><br />
<a href="#linguagem">2.5 Falta de conhecimento da linguagem com a qual se está programando</a><br />
<a href="#hardware">2.6 Falha no Hardware</a><br />
<a href="#debug">3. Como debugar um script</a><br />
<a href="#validacao">4 &#8211; Validações para evitar erros</a><br />
<a href="#excecao">5. Tratando erros com Exceções</a></p>
<h3><a name="o_que"">1. O que é tratamento de erros</a></h3>
<p>   Tratar um erro nada mais é do que preparar para rodar em qualquer situação ou, se não for possível, avisar por que não pôde ser executado. Tratando um erro você pode esperar uma situação e contorná-la ou, se não tiver jeito, finalizar a execução de uma forma segura e que não deixe o usuário sem saber o que está acontecendo. Ao fazer um tratamento de erros adequado, você pode preparar mensagens personalizadas para avisar os usuários que o sistema não pôde ser executado e notificar o erro ao administrador do site, para ele saber exatamente o que aconteceu e como proceder para corrigir o problema. Além disso, é útil para criação de estatísticas de erros.</p>
<h3><a name="boas">2. Boas maneiras para programar sem erros</a></h3>
<p>   Além de fazer um tratamento de erros adequado, você precisa programar de uma maneira que evite erros. Existem vários meios de gerar erros no seu sistema e, sabendo como evitá-los, você deixar seu sistema mais profissional e à prova de falhas. Possíveis causas de erros no sistema:</p>
<p> Programar de maneira errada<br />
 Esconder erros<br />
 Falta de uma lógica mais apurada e desenvolvida<br />
 Não pensar nos usuários<br />
 Falta de conhecimento na linguagem com a qual se está programando<br />
 Falha por parte de <em>hardware</em></p>
<p>   Explicarei um pouco sobre cada um.</p>
<h3><a name="errada">2.1 Programar de maneira errada</a></h3>
<p>   Esta tem suas principais causas: <em>preguiça</em>, <em>pressa</em>, <em>falta de planejamento</em> e/ou <em>falta de conhecimento</em>. A <em>preguiça</em> é porque na maioria das vezes o programador não quer saber como faz, mas, sim, entregar o sistema o mais rápido possível. Ele procura scripts prontos na Internet, só edita algumas coisas fáceis e acaba fazendo uma salada mista de vários sistemas prontos, tudo mal feito. O resultado é um sistema cheio de erros. Quanto mais o programador estudar e procurar entender para fazer seus sistemas, mais eles ficarão enxutos e livres de erros.</p>
<p>   A <em>pressa</em> é outra vilã. O programador acaba fazendo um monte de gambiarras e pensa assim: &#8220;Ah, depois de entregar o sistema eu arrumo os erros com calma. O mais importante é entregar no prazo!&#8221;, e acaba nunca arrumando. <em>Falta de planejamento</em> também é muito ruim e acontece quando o programador mal pegou o serviço e já quer fazer tudo de uma vez, sem pensar em como o desenvolverá. Como resultado, acaba fazendo o sistema, depois o banco de dados, e depois sai costurando as falhas até deixar tudo funcionando. Tenha calma e não se apresse em fazer. Em um sistema bem feito, 70% dele é planejamento e o restante, escrever os códigos, modelar um banco de dados de forma correta, etc.</p>
<p>   Já a pior das causas é a <em>falta de conhecimento</em>, pois é comum pessoas mal saberem o que é um HTML e já querem programar em PHP. Em alguns casos, conseguem até clientes e sempre aparecem desesperadamente nos fóruns pedindo ajuda para fazer um sistema para eles. Consequentemente nunca farão um sistema bem feito, até aprenderem a fazê-los por conta própria. Outros programadores têm até certo conhecimento, mas não o usa, enquanto outros chegam a um limite e param, acreditando que não precisam aprender mais nada. Aí surgem com aquela frase: &#8220;Em time que está ganhando não se mexe!&#8221;. Já vi programadores com 40 anos nas costas que usam o mesmo sistema que aprenderam a fazer no passado. Não querem evoluir ou aprender coisas novas, e aí acabam escondendo erros em vez de tratá-los.</p>
<p>   Existem várias maneiras de se esconder erros no PHP e muitos têm abusado desses recursos. <strong>Não se devem esconder erros!</strong>. Claro que num site já publicado você não pode deixar que usuários vejam erros do seu sistema, mas nem por isso se deve escondê-los. Se o sistema tem falhas deixe uma mensagem avisando que logo ele estará funcionando, em vez disso, por exemplo, mostrando um erro grotesco e que não significa nada ao usuário leigo, além de expor informações internas do seu sistema, como por exemplo <em>Warning: mysql_connect() [function.mysql-connect]: Access denied for user &#8216;root&#8217;@'localhost&#8217; (using password: NO) in&#8230;</em></p>
<p>   Muitas vezes eu falo que esconder erros é a mesma coisa que varrer a sujeira para debaixo do tapete. Não vou entrar em detalhes na parte de boas maneiras ao programar, porque já publicamos um artigo sobre isso (<a href="http://forum.imasters.com.br/index.php?showtopic=214963" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showtopic=214963&amp;referer=');">leia-o aqui</a>).</p>
<h3><a name="esconder">2.2 Esconder Erros</a></h3>
<p>   Agora vou explicar como esconder um erro do PHP e como fazer para mostrar mensagens personalizadas. Os erros têm que ser escondidos em certos casos porque senão o PHP acaba mostrando mensagens de erros para o usuário, por exemplo:</p>
<p><strong>Exemplo 2.2.1 Operadores de controle de erro (retirado do <a href="http://www.php.net" target="_blank" onclick="urchinTracker('/outgoing/www.php.net?referer=');">Manual do PHP</a>)</strong><br />
   O PHP suporta um operador de controle de erro: o sinal &#8216;arroba&#8217; (@). Quando ele precede uma expressão em PHP, qualquer mensagem de erro que possa ser gerada por ela será ignorada.<br />
Se o recurso <em>track_errors</em> estiver habilitado, qualquer mensagem de erro gerada pela expressão será gravada na variável global <strong>$php_errormsg</strong>. Esta variável será sobrescrita em cada erro, assim verifique-a constantemente se você quiser usá-la.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">/* Erro intencional de arquivo */</span>
<span style="color: #000088;">$my_file</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><span style="color: #990000;">file</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'arquivo_nao_existente'</span><span style="color: #009900;">&#41;</span> or <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Falha abrindo arquivo: '<span style="color: #006699; font-weight: bold;">$php_errormsg</span>'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Isto funciona para qualquer expressão, não apenas para funções:</span>
<span style="color: #000088;">$valor</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><span style="color: #000088;">$carrinho</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$produto</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// você não receberá nenhum aviso se a chave $produto não existir.</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p><strong>Nota:</strong> o operador @ funciona somente em expressões. Uma regra simples para lembrar disso: se você pode pegar o valor de alguma coisa, você pode prefixar isso com o @. Assim, você pode prefixar chamadas de variáveis, funções e include()&#8217;s, constantes e afins. Você não pode prefixar definições de funções ou classe, estruturas condicionais como o if, foreach e assim por diante.</p>
<p><strong>Exemplo 2.2.2 Ocultar erro em conexões com banco de dados</strong><br />
Usando o @ você pode ocultar erros de conexões com o banco de dados:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #339933;">@</span><span style="color: #990000;">mysql_connect</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;root&quot;</span><span style="color: #009900;">&#41;</span> or <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Mensagem de erro&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Usando o <strong>@</strong> podemos ocultar a mensagem de erro do PHP, mas devemos, ainda, informar o usuário e exibir uma mensagem de erro personalizado, podendo usar CSS, imagens etc. O mesmo vale para erros na abertura de arquivos ou envio de e-mails.</p>
<p>   Outra maneira de ocultar erros é editando o PHP.INI na linha &#8220;display_errors = off&#8221;. Muitos programadores, por não saberem configurar corretamente o PHP.INI, deixam-no no padrão de instalação e, dependendo da versão do PHP, o display_errors está em &#8220;off&#8221;. O que recomendo é deixar em &#8220;on&#8221;, caso contrário, o PHP não irá mostrar os erros, caso ocorram. Eu vejo erros comuns pelos fóruns, tipo esse:</p>
<p><strong>Exemplo 2.2.3 Índice não encontrado</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$val</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span>val<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// erro não delimitou uma string com aspas ou apóstrofos</span></pre></td></tr></table></div>

<p>   Daí eu falo para o usuário que ele precisa delimitar as strings com aspas, por exemplo, $_POST["val"]. Mas o usuário acaba comentando: &#8220;Mas assim também funciona e não tem erro!&#8221;. Isso acontece porque o display_errors dele esta em &#8220;off&#8221; e por isso não consegue perceber o erro. O PHP entende, conforme o exemplo acima, que <strong>val</strong> é uma constante. Não a encontrando, assume como uma string e exibe um erro do tipo <strong>E_NOTICE</strong>.</p>
<p><strong>Exemplo 2.2.4 Ocultar erros com error_reporting() (retirado do <a href=""http://www.php.net"" target="_blank">Manual do PHP</a>)</strong>   A função error_reporting() define a diretiva error_reporting em tempo de execução. O PHP tem vários níveis de erros, usando essa função você pode definir o nível durante a execução do seu script. error_reporting() define o nível de erros que o PHP irá reportar, e retorna o nível antigo. O parâmetro nível pode usar um bitmask, ou constantes. É fortemente recomendado que você use constantes para assegurar compatibilidade com futuras versões. Como níveis de erros podem ser adicionados, o intervalo das constantes pode crescer, então os níveis de erros indicados anteriormente por inteiros podem não funcionar como esperado.<br />
Exemplo 1. Exemplos error_reporting()</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">// Desativa o relatório de todos os erros</span>
<span style="color: #990000;">error_reporting</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// Reporta erros simples</span>
<span style="color: #990000;">error_reporting</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">E_ERROR</span> <span style="color: #339933;">|</span> <span style="color: #009900; font-weight: bold;">E_WARNING</span> <span style="color: #339933;">|</span> <span style="color: #009900; font-weight: bold;">E_PARSE</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Reportar E_NOTICE pode ser bom também (para reportar variáveis não iniciadas</span>
<span style="color: #666666; font-style: italic;">// ou erros de digitação em nomes de variáveis ...)</span>
<span style="color: #990000;">error_reporting</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">E_ERROR</span> <span style="color: #339933;">|</span> <span style="color: #009900; font-weight: bold;">E_WARNING</span> <span style="color: #339933;">|</span> <span style="color: #009900; font-weight: bold;">E_PARSE</span> <span style="color: #339933;">|</span> <span style="color: #009900; font-weight: bold;">E_NOTICE</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Reportar todos os erros exceto E_NOTICE</span>
<span style="color: #666666; font-style: italic;">// Este é o valor padrão no php.ini</span>
<span style="color: #990000;">error_reporting</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">E_ALL</span> ^ <span style="color: #009900; font-weight: bold;">E_NOTICE</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Reporta todos os erros (bitwise 63 deve ser usado no PHP 3)</span>
<span style="color: #990000;">error_reporting</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">E_ALL</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// O mesmo que error_reporting(E_ALL);</span>
<span style="color: #990000;">ini_set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'error_reporting'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">E_ALL</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>    Os níveis de erros disponíveis estão listados abaixo. A descrição deles está em constantes predefinidas. </p>
<p> 1 E_ERROR<br />
 2 E_WARNING<br />
 4 E_PARSE<br />
 8 E_NOTICE<br />
 16 E_CORE_ERROR<br />
 32 E_CORE_WARNING<br />
 64 E_COMPILE_ERROR<br />
 128 E_COMPILE_WARNING<br />
 256 E_USER_ERROR<br />
 512 E_USER_WARNING<br />
 1024 E_USER_NOTICE<br />
 2047 E_ALL<br />
 2048 E_STRICT</p>
<p><strong>Atenção</strong><br />
A partir do PHP 5.0.0, E_STRICT com o valor 2048 está disponível. E_ALL NÃO mostra erros do nível E_STRICT.</p>
<p><strong>Recomendo deixar error_reporting(E_ALL), para mostrar todos os tipos de erros.</strong></p>
<h3><a name="falta">2.3 Falta de uma lógica mais apurada e desenvolvida</a></h3>
<p>   Agora falando sobre lógica! Muitos erros acontecem também por falta de uma lógica correta, ou seja, programam de maneira errada, fazem gambiarra <strong>(famosa POG &#8211; Programação Orientada à Gambiarras)</strong>) ou complicam demais algo que poderia ser mais simples. Já vi muitos usuários não saberem manipular datas, como somar, subtrair, etc. Acabam fazendo cada loucura com uma coisa simples. Falta de lógica pode fazer com que o sistema fique com erros e, por azar, o programador não percebe até que o erro aconteça.</p>
<h3><a name="usuarios">2.4 Não pensar nos usuários</a></h3>
<p>  Não pensar nos usuários também pode fazer com que o sistema tenha erros. Um exemplo disso é o programador ter um micro de último tipo, e configurar o PHP.INI a seu gosto, com programas atualizados e acaba desenvolvendo pensando só nele. Esquece que outros usuários que irão usar o sistema não têm o mesmo recurso. Por exemplo: o programador faz um sistema usando PHP 5.2, Apache 2.2.4, Mysql 5 e disponibiliza o sistema para outros usuários e o coitado do usuário baixa o sistema e vai rodar num servidor com PHP 4 e Mysql 3 (a grande maioria dos servidores de hospedagem demoram para se atualizarem). Aí o sistema não funciona e aparecerá um monte de mensagens de erros e o usuário nem sabe o porquê. Não estou falando que não se deve programar usando as últimas versões, mas tem que ver pra qual situação será usado o sistema e verificar se o sistema está apto a rodar na plataforma em que foi instalado.</p>
<h3><a name="linguagem">2.5 Falta de conhecimento da linguagem com a qual se está programando</a></h3>
<p>   Falta de conhecimento na linguagem PHP também faz o sistema ter muitos erros. Muitas vezes o usuário é até esforçado, mas por falta de conhecimento não sabe identificar um erro ou um problema e muito menos fazer de um jeito melhor. Acaba pegando scripts prontos para aprender, mas estes também estão sujeitos a erros e o usuário vai querer editar, deixando-o cada vez pior. Por falta de conhecimento na linguagem também acontecem muitos erros de concatenação de strings, tags PHP, ou juntar HTML + PHP, banco de dados, entre outras coisas. Nesse tipo de coisa é muito fácil de cometer erros, principalmente se o usuário for inexperiente.<br />
   É importante estudar muito, acompanhar os novos recursos e buscar conhecimento em fontes sérias. Só assim evita-se dor de cabeça ou mesmo a perda de espaço no mercado de trabalho.</p>
<h3><a name="hardware">2.6 Falha no Hardware</a></h3>
<p>   E por último, erros também acontecem independente do sistema estar perfeito ou não. Pode ser que o servidor esteja em manutenção, ou outros problemas relacionados a hardware etc. Por esse motivo que, mesmo você fazendo um ótimo tratamento de erros, o sistema não conseguirá ser executado. Falarei de exceções logo mais à frente.</p>
<h3><a name="debug">3. Como debugar um script</a></h3>
<p>   Para testar um script e ver se ele está funcionando corretamente, há várias maneiras. A primeira delas é testar num servidor local. Para desenvolver, sempre deixe essas opções configuradas no php.ini:</p>
<p> display_errors = On<br />
 display_startup_errors = On<br />
 error_reporting  =  E_ALL<br />
 log_errors = On<br />
 track_errors = On<br />
 register_globals = Off</p>
<p>   Via script você pode fazer assim:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #339933;">@</span><span style="color: #990000;">ini_set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;display_errors&quot;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">@</span><span style="color: #990000;">ini_set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;log_errors&quot;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">@</span><span style="color: #990000;">ini_set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;error_reporting&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">E_ALL</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Em versões do PHP igual ou anterior à 4.2.3 era possível setar a diretiva register_globals via script, mas agora só via PHP.INI ou .htaccess. Via .htaccess é assim:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">php_flag register_globals off</pre></td></tr></table></div>

<p>   Agora, com tudo preparado, só resta testar o sistema. Existem vários editores com recursos para debugar um script, como por exemplo o <a href="http://www.waterproof.fr/" target="_blank" onclick="urchinTracker('/outgoing/www.waterproof.fr/?referer=');">PHPEdit da WaterProof</a>, o editor da <a href="http://www.zend.com" target="_blank" onclick="urchinTracker('/outgoing/www.zend.com?referer=');">Zend</a> ou o da <a href="http://www.maguma.com/" target="_blank" onclick="urchinTracker('/outgoing/www.maguma.com/?referer=');">Maguma</a>.</p>
<h3><a name="validacao">4 &#8211; Validações para evitar erros</a></h3>
<p>   Um bom tratamento de erros precisa prever vários tipos de erros e, pra isso, existem funções específicas, como por exemplo:</p>
<p> <a href="http://www.php.net/file_exists" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/file_exists?referer=');">file_exists</a> &#8211; serve para verificar se um arquivo existe<br />
 <a href="http://www.php.net/defined" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/defined?referer=');">defined</a> &#8211; serve para verificar se uma constante foi definida.<br />
 <a href="http://www.php.net/isset" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/isset?referer=');">isset</a> &#8211; verifica se uma variável existe.<br />
 <a href="http://www.php.net/is_array" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_array?referer=');">is_array</a> &#8211; verifica se a variável é um array<br />
 <a href="http://www.php.net/is_resource" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_resource?referer=');">is_resource</a> &#8211;  verifica se a variável é um resource<br />
 <a href="http://www.php.net/is_numeric" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_numeric?referer=');">is_numeric</a>  &#8211;  verifica se a variável é um número ou uma string numérica.<br />
 <a href="http://www.php.net/is_uploaded_file" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_uploaded_file?referer=');">is_uploaded_file</a> &#8211; verifica se o arquivo foi uploaded via HTTP POST.<br />
<a href="http://www.php.net/is_writable" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_writable?referer=');">is_writable</a> &#8211; verifica se pode escrever para o arquivo (writable).<br />
 <a href="http://www.php.net/version_compare" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/version_compare?referer=');">version_compare</a> &#8211; Compara a versão do php.<br />
 <a href="http://www.php.net/extension_loaded" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/extension_loaded?referer=');">extension_loaded</a> &#8211; verifica se a extensão foi habilitada.</p>
<p>   Com essas funções você pode testar, por exemplo, se um arquivo existe, antes de incluí-lo. Caso não exista, você pára o script e dá um aviso para o usuário. Outro exemplo: antes de gravar um arquivo texto, você verifica se ele pode ser escrito, ou antes de usar uma variável teste, se ela existe com isset()<br />   Outra validação muito importante é validar se o formulário foi enviado, assim evitando erro, por exemplo:</p>
<p><strong>Exemplo 4.1 Verificando se um formulário foi enviado</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">getenv</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;REQUEST_METHOD&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;POST&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//...faça tal coisa</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>   Se for get só mudar para GET, assim você testa se o formulário foi enviado.<br />
   Outra dica importante é testar se a variável existe caso venha de algum formulário:</p>
<p><strong>Exemplo 4.2 Verificando se uma variável foi inicializada</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$campo</span> <span style="color: #339933;">=</span> <span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;campo&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> ? <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;campo&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Exemplo 4.2 Incluindo um arquivo sem verificação</strong><br />
De tratamento de erros:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">require</span> <span style="color: #0000ff;">&quot;arquivo.php&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Mas e se o arquivo nao existir? Iria dar erro, então o mais correto é:</p>
<p><strong>Exemplo 4.3 Incluindo um arquivo com verificação</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">file_exists</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;arquivo.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">require</span> <span style="color: #0000ff;">&quot;arquivo.php&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p><strong>Exemplo 4.4 Desabilitando magic_quotes</strong><br />
   Programar dependente de magic_quotes não é recomendando, visto que o site ou sistema poderá não funcionar corretamente caso seja hospedado em um servidor com configuração divergente da que foi adotada para os testes locais. Os erros mais comuns são na inserção de valores em um banco de dados. Além disso, a partir do PHP 6, a diretiva magic_quotes_gpc não existirá mais e, por isso, é recomendado programar desabilitando este recurso. Esta diretiva não pode ser alterada através da função ini_set, devendo ser configurada diretamente no PHP.INI ou, se também possível, através do .htaccess, da seguinte forma:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">php_flag magic_quotes_gpc Off</pre></td></tr></table></div>

<p>   Como alternativa, você pode utilizar a função abaixo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> remove_magic_quotes<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">get_magic_quotes_gpc</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$_GET</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_map</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;remove_mq&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$_POST</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_map</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;remove_mq&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$_REQUEST</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_map</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;remove_mq&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_REQUEST</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$_COOKIE</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_map</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;remove_mq&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_COOKIE</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> remove_magic_quotes<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span><span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">return</span> <span style="color: #990000;">is_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span> ? <span style="color: #990000;">array_map</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;remove_magic_quotes&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span> <span style="color: #990000;">stripslashes</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>   Basicamente, a função verifica se a diretiva magic_quotes está habilitada e, então, varre pelos dados dos arrays globais inicializados (enviados por um formulário, por exemplo), eliminando os escapes dos caracteres. Preferencialmente, esta função deve ser chamada num arquivo de inicialização do sistema ou site.</p>
<h3><a name="excecao">5. Tratando erros com Exceções</a></h3>
<p>   A partir da versão 5 do PHP, pode-se tratar erros usando <a href="http://www.php.net/manual/pt_BR/language.exceptions.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/language.exceptions.php?referer=');">Exceções</a>. Com o uso desse recurso, podemos manipular os erros com mais precisão, facilitando, por exemplo, a criação de um log de erros contendo o nome do arquivo e a linha em que o erro ocorreu.<br />
   A classe <strong>Exception</strong> pode ser extendida a uma outra, viabilizando a personalização de mensagens de erro e a criação de uma classe para cada tipo de exceção. Por exemplo: é possível termos uma classe para manipular erros relacionados a banco de dados, outra para o manuseio de arquivos, de imagens, etc.<br />
   Uma exceção deve ser disparada (<em>thrown</em>) dentro de um bloco <strong>try{}</strong>. Em seguida, deve ser pega (<em>catched</em>) usando o bloco <strong>catch{}</strong>.</p>
<p><strong>Exemplo 5.1: Usando exceções para capturar um possível erro na conexão com um banco de dados MySQL</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">try <span style="color: #009900;">&#123;</span>
   <span style="color: #666666; font-style: italic;">//usamos o arroba para ocultar o possível erro retornado pelo PHP</span>
   <span style="color: #339933;">@</span><span style="color: #000088;">$MySQLi</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MySQLi<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;user&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;pass&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;db_name&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$MySQLi</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #666666; font-style: italic;">//se conexão falhar</span>
      <span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao realizar a conexão com o banco de dados&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$e</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #990000;">exit</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>   Se a conexão falhar, será disparada uma exceção, que será, posteriormente, pega no seu bloco catch correspondente. Nesse bloco, devemos colocar o nome da classe de exceção utilizada e criar uma variável, a qual será uma instância da exceção.</p>
<p>   Para obter mais informações sobre exceções, veja o link abaixo:<br />
   <a href="http://www.php.net/manual/pt_BR/language.exceptions.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/language.exceptions.php?referer=');">http://www.php.net/manual/pt_BR/language.exceptions.php</a></p>
<p><strong>Colaboraram neste artigo:</strong><br />
<a href="http://forum.imasters.com.br/index.php?showuser=18845" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showuser=18845&amp;referer=');">Anderson Mello</a><br />
<a href="http://forum.imasters.com.br/index.php?showuser=34746" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showuser=34746&amp;referer=');">Beraldo</a><br />
<a href="http://forum.imasters.com.br/index.php?showuser=13485" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showuser=13485&amp;referer=');">Fabyo</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/tratamento-de-erros-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Boas Práticas ao Programar</title>
		<link>http://www.rberaldo.com.br/blog/boas-praticas-ao-programar-2/</link>
		<comments>http://www.rberaldo.com.br/blog/boas-praticas-ao-programar-2/#comments</comments>
		<pubDate>Wed, 06 May 2009 00:13:00 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Boas Práticas]]></category>
		<category><![CDATA[programação correta]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/2009/05/05/boas-praticas-ao-programar-2/</guid>
		<description><![CDATA[Artigo sobre boas práticas de programação. O artigo usa a linguagem PHP, mas as técnicas podem ser aplicadas a qualquer outra linguagem.]]></description>
			<content:encoded><![CDATA[<p>Postarei aqui um artigo que eu e outros membros do Fórum iMasters escrevemos. É uma leitura essencial para qualquer programador. As práticas aplicam-se a diversas linguagens, mas neste caso, o foco principal é o PHP.</p>
<p>Boa leitura a todos!</p>
<p>Fonte: <a href="http://forum.imasters.uol.com.br/index.php?showtopic=214963" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.uol.com.br/index.php?showtopic=214963&amp;referer=');">http://forum.imasters.uol.com.br/index.php?showtopic=214963</a> </p>
<p><span id="more-12"></span></p>
<h3>Índice</h3>
<p><a href="#intro">1. Introdução</a><br />
<a href="#tags">2. Utilize sempre as tags completas</a><br />
<a href="#indent">3. Indentação</a><br />
<a href="#exist">4.  Funções para verificar a existência de variáveis e os seus tipos</a><br />
<a href="#cast">5. Tipos de dados e <em>casting</em></a><br />
<a href="#pattern">6. Adotar padrões para nomes de funções, classes, constantes e variáveis</a><br />
<a href="#e_all">7. Codificar usando exibição de erros E_ALL</a><br />
<a href="#arroba">8. Não ocultar erros utilizando @ ([arroba])</a><br />
<a href="#register_globals">9. Não codificar dependendo de register_globals</a><br />
<a href="#init">10. Criar arquivo de inicialização</a><br />
<a href="#atualizar_se">11. Mantenha-se sempre atualizado</a><br />
<a href="#apendices">Apêndices</a><br />
<a href="#apendice_a">Apêndice A. Sobre o php.ini</a><br />
<a href="#apendice_b">Apêndice B. Palavras reservadas</a><br />
<a href="#apendice_c">Apêndice C. Funções úteis para verificação de variáveis, diretórios e outros</a></p>
<h3><a name="intro">1. Introdução</a></h3>
<p>   Muitas das dicas abaixo valem para qualquer linguagem de programação, mas a abordagem principal é voltada para programação em PHP. Para quem quer ser um bom profissional não basta conhecer dezenas de linguagens diferentes e decorar as milhares de funções disponíveis para cada uma delas. Algo que muitos deixam de lado são os cuidados ao formatar o código, organizando-o e documentando-o adequadamente. Isso contribui, em muito, à alteração e à leitura do mesmo por outros profissionais, poupando tempo e permitindo fácil seqüência ao projeto.</p>
<p>   Vamos a algumas dicas recomendadas por vários profissionais da área. Todas elas devem ser consideradas também como referências para os próximos artigos que serão publicados aqui no fórum.</p>
<h3><a name="tags">2. Utilize sempre as tags completas</a></h3>
<p>   O PHP aceita quatro tipos de tags:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
<span style="color: #000000; font-weight: bold;">&lt;?</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
 <span style="color: #000000; font-weight: bold;">&lt;script language</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;php&quot;</span><span style="color: #339933;">&gt;&lt;/</span>script<span style="color: #339933;">&gt;</span>
<span style="color: #000000; font-weight: bold;">&lt;%</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></td></tr></table></div>

<p> A primeira opção é a padrão e preferencial, mas muitos programadores utilizam a segunda opção, por ser mais curta. Com ela, há também a possibilidade de usar esta sintaxe para exibir uma informação:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?=</span> <span style="color: #0000ff;">&quot;Hello World!&quot;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
// equivale a
<span style="color: #000000; font-weight: bold;">&lt;?</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Hello World!&quot;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p> Apesar disso, a utilização desse tipo de tag também não é recomendada, porque pode estar desabilitada no servidor, ou seja, quando a diretiva <strong>short_open_tag</strong> estiver em <strong>off</strong>, fazendo com que o script não seja interpretado.</p>
<p> A terceira opção não é muito comum, mas não é afetada pela diretiva <strong>short_open_tag</strong>, sendo tão segura quanto a primeira. As tags ASP <% %>, que também devem ser evitadas, só serão interpretadas se a diretiva <strong>asp_tags</strong> estiver em <strong>on</strong>, o que é pouco comum, visto que o seu valor padrão é <strong>off</strong>.</p>
<p><strong>Mais detalhes:</strong><br />
<a href="http://www.php.net/manual/pt_BR/language.basic-syntax.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/language.basic-syntax.php?referer=');">http://www.php.net/manual/pt_BR/language.basic-syntax.php</a></p>
<h3><a name="indent">3. Indentação</a></h3>
<p>   Uma boa indentação facilita a organização e a leitura do código. Veja os seguintes exemplos:</p>
<p><strong>Exemplo 3.1 Código em linha única e sem indentação</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">4</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Hello World!&quot;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><strong>Exemplo 3.2 Código sem indentação</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">4</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Hello World!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><strong>Exemplo 3.3 Código com indentação adequada</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span> <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">4</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Hello World!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>   Com os exemplos acima, podemos notar que a ausência de identação em um pequeno trecho de código pode não fazer diferença, mas tente imaginar 300 ou 400 linhas sem identação. Melhor ainda (ou pior), imagine fazer uma alteração em um script escrito nesse formato&#8230;<br />   Alguns podem, inclusive, pensar que reduzindo o número de linhas de código, facilita-se a navegação e a leitura do mesmo.<br />
   Uma boa identação é a que você adotar como padrão. O recomendado, e também adotado por muitos, é uma indentação de quatro espaços. Dê atenção especial às estruturas de controle, onde o &#8220;aninhamento&#8221; delas podem causar confusão de leitura.</p>
<p><strong>Exemplo 3.4 Código sem indentação</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$b</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$a</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #666666; font-style: italic;">//código</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
<span style="color: #666666; font-style: italic;">//código</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><strong>Exemplo 3.5 Código com indentação adequada</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$b</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$a</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">//código</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">//código</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>   Nos exemplos 3.4 e 3.5 é possível perceber mais claramente o problema da falta de indentação.</p>
<h3><a name="exist">4.  Funções para verificar a existência de variáveis e os seus tipos</a></h3>
<p>   É importante verificar se uma variável, constante ou mesmo chave de array associativo foi inicializado, antes de resgatar o seu valor e utilizá-lo em algum processamento. Isso evita resultados inesperados. Veja o exemplo abaixo:</p>
<p><strong>Exemplo 4.1</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'a'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot; World!&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$a</span><span style="color: #339933;">.</span><span style="color: #000088;">$b</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Considerando-se que o valor de $a tenha sido enviado por um formulário, pelo método POST, e esse valor seja &#8220;Hello&#8221;, a saída será &#8220;Hello World!&#8221;. Porém, se nenhum valor for preenchido, teremos um resultado inesperado, podendo ser gerada uma notificação de inexistência de variável. Para testar se a variável foi iniciada, utilizamos <a href="http://www.php.net/isset" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/isset?referer=');">isset()</a>.</p>
<p><strong>Exemplo 4.2</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'a'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'a'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Hi&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot; World!&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$a</span><span style="color: #339933;">.</span><span style="color: #000088;">$b</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Outra forma, mais curta, é utilizar o <strong>operador condicional ternário</strong> (ou somente <strong>operador ternário</strong>).</p>
<p><strong>Exemplo 4.3 &#8211; Utilizando o operador ternário</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'a'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> ? <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'a'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;Hi&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot; World!&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$a</span><span style="color: #339933;">.</span><span style="color: #000088;">$b</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>   Se a primeira expressão retornar verdadeiro (TRUE), o segundo bloco é executado. Caso contrário, executa-se o terceiro.   Dessa forma, caso a variável não tenha sido enviada pelo formulário, atribuímos a ela o valor &#8220;Hi&#8221;, produzindo a saída &#8220;Hi World!&#8221;. Para fazer esse tipo de verificação com constantes, utilizamos a função <a href="http://www.php.net/defined" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/defined?referer=');">defined()</a>.</p>
<p><strong>Exemplo 4.4</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CAMINHO&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;www/meudiretorio/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">defined</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CAMINHO&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;A constante já foi definida.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;A constante não foi definida.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Confira no Apêndice uma lista de funções úteis para verificação de tipos de variáveis, existência de diretórios, funções e outros.</p>
<p><strong>Mais detalhes:</strong><br />
<a href="http://www.php.net/manual/pt_BR/ref.variables.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/ref.variables.php?referer=');">http://www.php.net/manual/pt_BR/ref.variables.php</a></p>
<h3><a name="cast">5. Tipos de dados e <em>casting</em></a></h3>
<p>   Ao desenvolvermos um sistema ou site, deparamo-nos com o uso de diversos tipos de variáveis, como <em>strings</em>, <em>arrays</em>, <em>booleans</em>, dentre outros. Como o PHP não suporta a definição de tipos de variáveis nas declarações das mesmas, em determinados momentos, uma variável que deveria conter como valor um número inteiro, pode receber uma string. Isso pode gerar erros sileciosos, comprometendo o funcionamento do código. Veja o exemplo:</p>
<p><strong>Exemplo 5.1</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Retorna 'integer'</span>
<span style="color: #000088;">$var</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">print</span> <span style="color: #990000;">gettype</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Retorna 'string'</span>
<span style="color: #000088;">$var</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;6&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">print</span> <span style="color: #990000;">gettype</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Usamos a função <a href="http://www.php.net/gettype" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/gettype?referer=');">gettype()</a> para retornar o tipo de variável declarada. No segundo trecho temos a declaração da mesma variável <strong>$var</strong>, que passa a receber o tipo de variável <em>string</em>. Este dado é convertido automaticamente ao fazer uma soma, por exemplo, voltando novamente a ser um valor do tipo inteiro. Para contornar esse tipo de situação e evitar surpresas, recomenda-se moldar o tipo de variável, também chamado de <em><strong>casting</strong></em>, assegurando assim que a variável será do tipo esperado. Para isso, pode-se utilizar a função <a href="http://www.php.net/settype" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/settype?referer=');">settype()</a>.</p>
<p><strong>Exemplo 5.2</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Retorna 'integer', mesmo com o valor declarado como 'string'</span>
<span style="color: #000088;">$var</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;6&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">settype</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$var</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'integer'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">print</span> <span style="color: #990000;">gettype</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   A moldagem de tipos também pode ser feita no momento da declaração da variável, antecedendo o seu valor com o tipo desejado, entre parênteses:</p>
<p><strong>Exemplo 5.3</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Define o tipo 'integer'</span>
<span style="color: #000088;">$var</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>integer<span style="color: #009900;">&#41;</span> <span style="color: #0000ff;">&quot;6&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">print</span> <span style="color: #990000;">gettype</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Mais detalhes:<br />
<a href="http://www.php.net/manual/pt_BR/language.types.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/language.types.php?referer=');">http://www.php.net/manual/pt_BR/language.types.php</a></p>
<h3><a name="pattern">6. Adotar padrões para nomes de funções, classes, constantes e variáveis</a></h3>
<p>   Mesmo que as maiores diferenças sejam notadas em grandes projetos, adotar padrões ao declarar funções, variáveis etc. auxilia o desenvolvimento, pois se evita a dúvida ou mesmo erros, por exemplo, ao chamar funções que não existam, simplesmente por se ter um nome confuso ou uma falta de padrão.<br />
   Você deve estar ciente da padronização que irá fazer, e respeitá-la rigorosamente em todo o site ou sistema. Um exemplo:</p>
<p><strong>Exemplo 6.1</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> primeira_funcao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">//...</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> segundaFuncao<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">//...</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>   Programar sem um padrão, como no exemplo acima, compromete o desenvolvimento, pois será muito fácil acabar chamando por funções inexistentes (nomes diferentes do esperado). É muito importante analisar os padrões já utilizados por outros programadores ou desenvolver seu próprio padrão e seguí-lo à risca, garantindo assim um projeto fluente.<br />
   Essa mesma situação pode ser enfrentada para nomes de constantes, variáveis ou classes. Por isso, é importante seguir um padrão, tal como o exemplo abaixo:</p>
<p><strong>Exemplo 6.2</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$var</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">7</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$minhaVar</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;PHP&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CONSTANTE&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Valor da constante&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SEGUNDA_CONSTANTE&quot;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> minhaFuncao<span style="color: #009900;">&#40;</span><span style="color: #000088;">$argumento</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;&lt;b&gt;<span style="color: #006699; font-weight: bold;">$argumento</span>&lt;b&gt;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
classe MinhaClasse <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">//...</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Para o nome de variáveis, prefira utilizar nomes sempre em minúsculas. Para variáveis com palavras compostas, separe-as alterando as palavras seguintes com letra inicial maiúscula. Nomes de constantes preferencialmente devem ser declarados em maiúsculas, utilizando underline (&#8220;_&#8221;) como separador de palavras.<br />
   As funções e seus argumentos, assim como as classes, devem ser declaradas utilizando-se o mesmo padrão para as variáveis. Como forma de diferenciar as classes de funções, estas devem ter seus nomes com a inicial também em maiúscula.</p>
<h3><a name="e_all">7. Codificar usando exibição de erros E_ALL</a></h3>
<p>   Durante a estruturação de seu código, é muito importante manter as diretivas <strong>error_reporting</strong> em <strong>E_ALL</strong> e <strong>display_errors</strong> em <strong>on</strong>. Isso faz com que todos os possíveis erros sejam exibidos, para que você possa corrigi-los.<br />
   Não é necessário acessar o arquivo php.ini para alterar esses valores, basta usar a função <a href="http://www.php.net/ini_set" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/ini_set?referer=');">ini_set()</a>, como no exemplo abaixo:</p>
<p><strong>Exemplo 7.1</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #990000;">ini_set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'error_reporting'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">E_ALL</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">ini_set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'display_errors'</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// restante do código</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Deve-se inserir essas mudanças sempre antes do restante do código, para que elas afetem o script inteiro.   </p>
<p>Mais detalhes<br />
<a href="http://www.php.net/manual/pt_BR/ref.errorfunc.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/ref.errorfunc.php?referer=');">http://www.php.net/manual/pt_BR/ref.errorfunc.php</a></p>
<h3><a name="arroba">8. Não ocultar erros utilizando @ ([arroba])</a></h3>
<p>   É desaconselhável o uso excessivo do operador de controle de erros (@, &#8220;arroba&#8221;). Esse operador somente deve ser usado nos casos em que a ocorrência de erro seja uma excessão, como na função mail(), funções de conexão com banco de dados e outras.</p>
<p><strong>Exemplo 8.1</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!@</span><span style="color: #990000;">mysql_connect</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;servidor&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;usuario&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;senha&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #990000;">die</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao conectar com o banco de dados MySQL&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span></pre></td></tr></table></div>

<p>   Considerando-se que os argumentos da função mysql_connect() acima estejam corretos, erros de conexão tornam-se uma exceção, como em caso de servidor fora do ar.<br />
   A partir do PHP 5, é possível manusear erros por meio de <a href="http://www.php.net/manual/pt_BR/language.exceptions.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/language.exceptions.php?referer=');">Exceções</a>, mas esse tema não será abordado neste artigo.</p>
<p><strong>Nota importante: </strong><br />
Atualmente, o operador de controle de erro &#8220;@&#8221; sempre desativa mensagens de erro, mesmo para erros críticos, que terminam a execução de scripts. Além de outras coisas, isto significa que se você usar &#8220;@&#8221; para suprimir erros de certas funções e elas não estiverem disponíveis ou com tipos incorretos, o script vai parar exatamente aí sem nenhuma indicação da razão.</p>
<p><strong>Mais detalhes:</strong><br />
<a href="http://www.php.net/manual/pt_BR/language.operators.errorcontrol.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/language.operators.errorcontrol.php?referer=');">http://www.php.net/manual/pt_BR/language.operators.errorcontrol.php</a></p>
<h3><a name="register_globals">9. Não codificar dependendo de register_globals</a></h3>
<p>   A register_globals é uma diretiva que passou a estar desabilitada (Off), por padrão, a partir do PHP 4.2.0. Essa diretiva, quando habilitada no PHP.INI, faz com que as variáveis globais sejam registradas (inicializadas) diretamente no script em execução.</p>
<p><strong>Exemplo 9.1 valor inicializado por GET</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Script acessado com valor via GET</span>
<span style="color: #666666; font-style: italic;">//meu_script.php?var=Teste</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$var</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;A variável foi inicializada pela register_globals;
} else {
    print &quot;</span>A variável <span style="color: #000088;">$var</span> não foi inicializada<span style="color: #0000ff;">&quot;;
}</span></pre></td></tr></table></div>

<p>   O exemplo acima, apesar de inofensivo, pode sugerir a vulnerabilidade que o uso incorreto da diretiva register_globals pode acarretar. Imagine uma função que verifica a autenticação do usuário e define uma variável como verdadeira:</p>
<p><strong>Exemplo 9.2</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>usuario_logado<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$usuario_autenticado</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$usuario_autenticado</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">include</span> <span style="color: #0000ff;">&quot;menu.php&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Você não tem permissão.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>   Neste exemplo fica claro a brecha de segurança, pois basta inicializar a variável $usuario_autenticado como verdadeira (TRUE) ao acessar o script para que o menu esteja disponível, burlando a função de verificação de autenticação do usuário. Para corrigir este problema, basta simplesmente inicializar a variável como false. Além de uma boa prática, previne que o valor seja &#8220;forçado&#8221; a ser verdadeiro.</p>
<p><strong>Exemplo 9.3</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Inicializando a variável $usuario_autenticado</span>
<span style="color: #666666; font-style: italic;">//como false, evitando que a register_globals</span>
<span style="color: #666666; font-style: italic;">//interfira no código</span>
<span style="color: #000088;">$usuario_autenticado</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>usuario_logado<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$usuario_autenticado</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$usuario_autenticado</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">include</span> <span style="color: #0000ff;">&quot;menu.php&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Você não tem permissão.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3><a name="init">10. Criar arquivo de inicialização</a></h3>
<p>   Um arquivo de inicialização é útil para verificar a versão do PHP em que o script está sendo executado, suas configurações padrão e definir valores que serão usados em todo o sistema. Isso torna a execução mais segura e não suscetível a erros.<br />
   Os pontos mais importantes em um arquivo de inicialização de sistemas são:</p>
<p>*Versão do PHP em que o script está sendo executado;<br />
*Verificar se determinadas extensões foram carregadas, como mysql, mysqli, gd, etc;<br />
*Definir valores para diretivas do php.ini, como <strong>error_reporting</strong> e <strong>display_errors</strong>;<br />
*Definir constantes, como informações para conexão com bancos de dados, diretório-raiz do sistema e outras.</p>
<p><strong>Mais detalhes:</strong><br />
<a href="http://forum.imasters.com.br/index.php?showtopic=202215" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showtopic=202215&amp;referer=');">http://forum.imasters.com.br/index.php?showtopic=202215</a></p>
<h3><a name="atualizar_se">11. Mantenha-se sempre atualizado</a></h3>
<p>   A linguagem PHP está em constante atualização, sendo frequentemente disponíveis novas atualizações de versões para download. Por isso, acesse periodicamente o site oficial do PHP (<a href="http://www.php.net" target="_blank" onclick="urchinTracker('/outgoing/www.php.net?referer=');">http://www.php.net</a>) e verifique se não há uma versão mais recente do que a qual você está utilizando no momento. Se houver, baixe-a e instale-a imediatamente. Para facilitar esta verificação, segue abaixo um script desenvolvido pelo Fabyo. Além de verificar, ele exibe também os links para download.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$url</span>  <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://www.php.net/downloads.php&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$file</span> <span style="color: #339933;">=</span> <span style="color: #339933;">@</span><span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">preg_match_all</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#&lt;h2&gt;Windows Binaries&lt;\/h2&gt;(.+?)&lt;/ul&gt;#si&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$file</span><span style="color: #339933;">,</span> <span style="color: #000088;">$matches</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">preg_match_all</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;#&lt;a href=(.+?)&gt;(.+?)&lt;\/a&gt;#si&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$matches2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$php</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;PHP&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$matches2</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$php</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;zip package&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$php</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$php</span> <span style="color: #339933;">=</span> <span style="color: #990000;">trim</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$php</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">version_compare</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">phpversion</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$php</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;&lt;&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;-1&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Sua versao do php esta desatualizada baixe a nova versao:&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$matches2</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;&lt;br /&gt;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$matches2</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span> 
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;img src=<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #339933;">.</span> <span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;PHP_SELF&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;?=&quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">php_logo_guid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\&quot;</span> alt=<span style="color: #000099; font-weight: bold;">\&quot;</span>Logo<span style="color: #000099; font-weight: bold;">\&quot;</span> /&gt;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;br /&gt;Sua versão esta atualizada&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>   Também é importante prestar atenção às alterações feitas em cada versão, para que um script não gere incompatibilidade entre duas ou mais vesões do PHP. As duas mais importantes mudanças que podem afetar a execução de um código PHP são estas:</p>
<p>* A extinção das variáveis $HTTP_*_VARS (como $HTTP_GET_VARS e $HTTP_POST_VARS) e a criação das autoglobais (ou super globais) $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_REQUEST, e $_SESSION.<br />
* A mudança do valor padrão da diretiva <strong>register_globals</strong> de <strong>on</strong> para <strong>off</strong>.</p>
<p><strong>Mais detalhes:</strong><br />
<a href="http://br.php.net/manual/pt_BR/tutorial.oldcode.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/pt_BR/tutorial.oldcode.php?referer=');">http://br.php.net/manual/pt_BR/tutorial.oldcode.php</a><br />
<a href="http://br.php.net/manual/pt_BR/language.variables.predefined.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/pt_BR/language.variables.predefined.php?referer=');">http://br.php.net/manual/pt_BR/language.variables.predefined.php</a><br />
<a href="http://br.php.net/manual/pt_BR/security.globals.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/pt_BR/security.globals.php?referer=');">http://br.php.net/manual/pt_BR/security.globals.php</a></p>
<h3><a name="apendices">Apêndices</a></h3>
<h3><a name="apendice_a">Apêndice A. Sobre o php.ini</a></h3>
<p><a href="http://br.php.net/manual/pt_BR/ini.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/pt_BR/ini.php?referer=');">http://br.php.net/manual/pt_BR/ini.php</a></p>
<p>Entenda o PHP.INI (artigo publicado pelo <a href="http://forum.imasters.com.br/index.php?showuser=13485" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showuser=13485&amp;referer=');">Fabyo</a>): <a href="http://forum.imasters.com.br/index.php?showtopic=144987" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showtopic=144987&amp;referer=');">http://forum.imasters.com.br/index.php?showtopic=144987</a></p>
<h3><a name="apendice_b">Apêndice B. Palavras reservadas</a></h3>
<p><a href="http://br.php.net/manual/pt_BR/reserved.php" target="_blank" onclick="urchinTracker('/outgoing/br.php.net/manual/pt_BR/reserved.php?referer=');">http://br.php.net/manual/pt_BR/reserved.php</a></p>
<h3><a name="apendice_c">Apêndice C. Funções úteis para verificação de variáveis, diretórios e outros</a></h3>
<p>*<a href="http://www.php.net/is_array" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_array?referer=');">is_array()</a><br />
*<a href="http://www.php.net/is_bool" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_bool?referer=');">is_bool()</a><br />
*<a href="http://www.php.net/is_float" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_float?referer=');">is_float()</a><br />
*<a href="http://www.php.net/is_int" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_int?referer=');">is_int()</a><br />
*<a href="http://www.php.net/is_numeric" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_numeric?referer=');">is_numeric()</a><br />
*<a href="http://www.php.net/is_null" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_null?referer=');">is_null()</a><br />
*<a href="http://www.php.net/is_object" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_object?referer=');">is_object()</a><br />
*<a href="http://www.php.net/is_resource" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_resource?referer=');">is_resource()</a><br />
*<a href="http://www.php.net/is_string" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_string?referer=');">is_string()</a><br />
*<a href="http://www.php.net/is_dir" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_dir?referer=');">is_dir()</a><br />
*<a href="http://www.php.net/is_file" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/is_file?referer=');">is_file()</a><br />
*<a href="http://www.php.net/file_exists" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/file_exists?referer=');">file_exists()</a><br />
*<a href="http://www.php.net/function_exists" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/function_exists?referer=');">function_exists()</a><br />
*<a href="http://www.php.net/array_key_exists" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/array_key_exists?referer=');">array_key_exists()</a></p>
<p><strong>Colaboraram neste artigo:</strong></p>
<p><a href="http://forum.imasters.com.br/index.php?showuser=18845" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showuser=18845&amp;referer=');">Anderson Mello</a><br />
<a href="http://forum.imasters.com.br/index.php?showuser=34746" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showuser=34746&amp;referer=');">Beraldo</a><br />
<a href="http://forum.imasters.com.br/index.php?showuser=13485" target="_blank" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?showuser=13485&amp;referer=');">Fabyo</a><br />
Thiago Ferreira (tmferreira)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/boas-praticas-ao-programar-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

