<?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; PHP</title>
	<atom:link href="http://www.rberaldo.com.br/blog/tag/php/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>Wed, 25 Jan 2012 14:23:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
		<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>Arquivos .ini: processando arquivos de configuração com PHP</title>
		<link>http://www.rberaldo.com.br/blog/arquivos-ini-processando-arquivos-de-configuracao-com-php/</link>
		<comments>http://www.rberaldo.com.br/blog/arquivos-ini-processando-arquivos-de-configuracao-com-php/#comments</comments>
		<pubDate>Sun, 20 Feb 2011 19:27:04 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[arquivo]]></category>
		<category><![CDATA[configuração]]></category>
		<category><![CDATA[ini]]></category>
		<category><![CDATA[inicialização]]></category>
		<category><![CDATA[parse_ini_file]]></category>
		<category><![CDATA[processamento]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=393</guid>
		<description><![CDATA[Processamento de arquivos INI usando PHP e a função nativa parse_ini_file]]></description>
			<content:encoded><![CDATA[<p>Um formato de arquivo muito usado para armazenar diretrizes de configuração são os <a href="http://pt.wikipedia.org/wiki/INI_(formato_de_arquivo)" target="_blank" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/INI_formato_de_arquivo?referer=');">Arquivos .INI</a>, muito comum em plataformas Windows.</p>
<p>Normalmente são usados em sistemas desktop, mas é possível usá-lo para qualqquer tipo de aplicação. O PHP possui uma função nativa destinada ao processamento desse tipo de arquivo.</p>
<p><span id="more-393"></span></p>
<p>Antes de tudo, é bom entender a formatação de um arquivo INI. O <a href="http://pt.wikipedia.org/wiki/INI_(formato_de_arquivo)" target="_blank" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/INI_formato_de_arquivo?referer=');">artigo sobre arquivos INI da Wikipedia</a> explica muito bem essa formatação. Além disso, se você está lendo este post é porque tem familiaridade com o PHP e, consequentemente, com o arquivo <code>php.ini</code>, o arquivo de configuração do PHP, que é um arquivo INI.</p>
<p>Vamos considerar o arquivo INI abaixo, nomeado como <code>config.ini</code>.</p>
<pre>
; comentário da seção 1
[section 1]
config1 = "valor 1"

; comentário da seção 2
[section 2]
config2 = "valor 2"
</pre>
<p>Usaremos a função <a href="http://php.net/manual/en/function.parse-ini-file.php" target="_blank" onclick="urchinTracker('/outgoing/php.net/manual/en/function.parse-ini-file.php?referer=');"><code>parse_ini_file</code></a>, do PHP, para processarmos esse arquivo.</p>
<p>O protótipo da função é:</p>
<p><strong>array</strong> parse_ini_file ( string $filename [, bool $process_sections = false]);</p>
<p>O primeiro parâmetro é o nome  do arquivo a ser processado. O segundo, opcional, define se devem ser processadas as seções dos arquivos. O padrão é <strong>false</strong>. Caso passe-se o valor <strong>true</strong>, o array de retorno será multidimensional, sendo cada dimensão correspondente a cada seção do arquivo .ini.</p>
<p>Isso ficará mais claro ao rodarmos este script:</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: #000088;">$config</span> <span style="color: #339933;">=</span> <span style="color: #990000;">parse_ini_file</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'config.ini'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">print_r</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$config</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$configWithSections</span> <span style="color: #339933;">=</span> <span style="color: #990000;">parse_ini_file</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'config.ini'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">print_r</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$configWithSections</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A saída é:</p>
<pre>
Array
(
    [config1] => valor 1
    [config2] => valor 2
)
Array
(
    [section 1] => Array
        (
            [config1] => valor 1
        )

    [section 2] => Array
        (
            [config2] => valor 2
        )

)
</pre>
<p>O primeiro <code>print_r</code> exibe o array unidimensional, com todas as seções numa única dimensão do array. O segundo <code>print_r</code> exibe o array multidimensional, resultante do processamento que leva em conta as seções do arquivo .ini.</p>
<p>Com isso fica simples criar arquivos de inicialização que buscam configurações básicas em arquivos .ini.</p>
<p>Porém, tome cuidado ao usar arquivos .ini com informações sensíveis, como configurações de acesso a bancos de dados. Arquivos .ini podem ser acessados via URL, sendo possível visualizar seu conteúdo pelo navegador. Logo, opte por manter um arquivo ini fora do diretório público de sua aplicação (geralmente o <code>public_html</code>).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/arquivos-ini-processando-arquivos-de-configuracao-com-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>As Mensagens de Erros Mais Comuns do PHP</title>
		<link>http://www.rberaldo.com.br/blog/as-mensagens-de-erros-mais-comuns-do-php/</link>
		<comments>http://www.rberaldo.com.br/blog/as-mensagens-de-erros-mais-comuns-do-php/#comments</comments>
		<pubDate>Sat, 29 Jan 2011 13:00:23 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[comum]]></category>
		<category><![CDATA[erro]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[fatal]]></category>
		<category><![CDATA[mensagem]]></category>
		<category><![CDATA[message]]></category>
		<category><![CDATA[parse]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[undefined]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=351</guid>
		<description><![CDATA[Artigo mostrando as mensagens de erros ais comuns do PHP, com suas principais causas e soluções]]></description>
			<content:encoded><![CDATA[<p>As linguagens de programação geram mensagens de erros e <em>warnings</em>, que sempre informam o problema presente no código-fonte &#8211; quem conhece o <em><strong>Segmentation Fault</strong></em> do C/C++ pode querer discordar de mim :P -, de forma que a initerpretação correta dessas mensagens frequentemente indicam a forma adeequada de corrigir o problema.</p>
<p>Porém, poucos programadores iniciantes analisam essas mensagens, seja por falta de conhecimento ou preguiça mesmo. Ou até medo&#8230;</p>
<p>Vou mostrar aqui as mensagens de erro mais frequentes do PHP, junto com suas principais causas e soluções.</p>
<p><span id="more-351"></span></p>
<h3>Sumário</h3>
<p><a href="#enable_errors">Habilitando todas as mensagens de erro</a><br />
<a href="#err_op">Retirar o Operador de Controle de Erros</a><br />
<a href="#parse_error">Parse Error</a><br />
<a href="#undef_index">Undefined Index</a><br />
<a href="#undef_var">Undefined Variable</a><br />
<a href="#header">Cannot modify header information</a><br />
<a href="#undef_func">Call to undefined function</a><br />
<a href="#class_notfound">Class not found</a><br />
<a href="#undef_method">Call to undefined method</a><br />
<a href="#call_member_func">Call to a member function on a non-object</a><br />
<a href="#mysql_result_resource">supplied argument is not a valid MySQL result resource</a><br />
<a href="#foreach">Invalid argument supplied for foreach()</a><br />
<a href="#conclusao">Conclusão</a></p>
<p><a name="enable_errors"><br />
<h3>Habilitando todas as mensagens de erro</h3>
<p></a></p>
<p>Antes de tudo, é bom saber que o PHP é muito personalizável &#8211; o que às vezes pode ser um problema. É possível desabilitar todas as mensagens de erro, ou limitar somente a alguns níveis de erro. Não vou explicar os níveis de erro do PHP, pois não é o foco do texto. Porém deixarei links para referência.</p>
<p>Para habilitar todas as mensagens de erro do PHP, basta inserir este trecho no início do script:</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: #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>
<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: #339933;">|</span> <span style="color: #009900; font-weight: bold;">E_STRICT</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><a href="http://php.net/manual/en/function.ini-set.php" onclick="urchinTracker('/outgoing/php.net/manual/en/function.ini-set.php?referer=');">Documentação da função ini_set</a><br />
<a href="http://php.net/manual/en/function.error-reporting.php" onclick="urchinTracker('/outgoing/php.net/manual/en/function.error-reporting.php?referer=');">Documentação da função error_reporting</a><br />
<a href="http://php.net/manual/en/ref.errorfunc.php" onclick="urchinTracker('/outgoing/php.net/manual/en/ref.errorfunc.php?referer=');">Funções para manipulação de erros</a><br />
<a href="http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting" onclick="urchinTracker('/outgoing/www.php.net/manual/en/errorfunc.configuration.php_ini.error-reporting?referer=');">Descrição da diretiva <em>error_reporting</em> do php.ini</a><br />
<a href="http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors" onclick="urchinTracker('/outgoing/www.php.net/manual/en/errorfunc.configuration.php_ini.display-errors?referer=');">Descrição da diretiva <em>display_errors</em> do php.ini</a></p>
<p><a name="err_op"><br />
<h3>Retirar o Operador de Controle de Erros</h3>
<p></a></p>
<p>Outro ponto a ser observado é que é possível omitir erros no pHP usando o Operador de Controle de Erros, o famoso arroba (@). Esse operador existe para ser usado, mas use-o com cautela, quando for realmente necessário.</p>
<p><a href="http://www.rberaldo.com.br/blog/2009/05/05/boas-praticas-ao-programar-2/#arroba">Entenda quando usar o Operador de Controle de Erros (arroba &#8211; @)</a><br />
<a href="http://php.net/manual/en/language.operators.errorcontrol.php" onclick="urchinTracker('/outgoing/php.net/manual/en/language.operators.errorcontrol.php?referer=');">Documentação do Operador de Controle de Erros</a></p>
<p><a name="parse_error"><br />
<h3>Parse Error</h3>
<p></a></p>
<p><em>Parse Errors</em> ocorrem quando seu código possui erros de formatação, como caractere faltando ou em excesso.</p>
<p>Por exemplo:</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: #990000;">phpinfo</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>Retornará o erro:</p>
<pre>
Parse error:  syntax error, unexpected ')' in teste.php on line 2
</pre>
<p>A correção é sempre muito simples: analisar a linha onde o erro ocorre e procurar o acarctere indicado pelo erro. Pode estar faltando algo ou sobrando alguma coisa. Note que o erro pode não estra na linha indicada pela mensagem de erro. Pode estar na anterior. Por exemplo:</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: #b1b100;">echo</span> <span style="color: #0000ff;">'oi'</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'oi de novo'</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Mensagem de erro:</p>
<pre>
Parse error:  syntax error, unexpected T_ECHO, expecting ',' or ';' in teste.php on line 3
</pre>
<p>A mensagem diz que há erro na linha 3, mas é a linha 2 que gera problema, devido à falta do ponto-e-vírgula no final do <strong>echo</strong>. </p>
<p><a name="undef_index"><br />
<h3>Undefined Index</h3>
<p></a></p>
<p>Esse erro ocorre quando tenta-se acessar um índice inexistente de um array. Esse erro é muito comum com iniciantes usando Query String. O famoso exemplo:</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: #000088;">$pag</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'pag'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Se não existe a variável &#8220;pag&#8221; na URL, dará este erro:</p>
<pre>
PHP Notice:  Undefined index: pag in teste.php on line 2
</pre>
<p>Para evitar esse erro, sempre verifique se o índice existe. A função <a href="http://php.net/manual/en/function.isset.php" onclick="urchinTracker('/outgoing/php.net/manual/en/function.isset.php?referer=');">isset</a> resolve facilmente esse problema:</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: #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;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'pag'</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;">$pag</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'pag'</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;">$pag</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'valor padrão'</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>O código pode ser reescrito sda seguinte forma, usando o Operador Condicional Ternário:</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;">$pag</span> <span style="color: #339933;">=</span> <span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'pag'</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span> ? <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'pag'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #0000ff;">'valor_padrao'</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Mais sobre o Operador Ternário aqui:<br />
<a href="http://www.php.net/manual/pt_BR/language.operators.comparison.php" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/language.operators.comparison.php?referer=');">http://www.php.net/manual/pt_BR/language.operators.comparison.php</a></p>
<p><a name="undef_var"><br />
<h3>Undefined Variable</h3>
<p></a></p>
<p>Como o erro mostra claramente, isso ocorre quando se tenta usar uma variável não declarada (ou definida, no caso do 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: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$var</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Erro:</p>
<pre>
PHP Notice:  Undefined variable: var in teste.php on line 2
</pre>
<p>A solução não poderia der outra: criar a variável antes de usá-la.<br />
Logicamente, o erro pode ter ocorrido por um erro de digitação do nome da variável.</p>
<p><a name="header"><br />
<h3>Cannot modify header information</h3>
<p></a></p>
<p>Essa mensagem de erro está ligada a envio de cabeçalhos HTTP, o que envolve <em>sessions</em>, <em>cookies</em>, a própria função <a href="http://www.php.net/manual/pt_BR/function.header.php" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/function.header.php?referer=');"><em>header</em></a>, do PHP.</p>
<p>O envio de cabeçalhos HTTP devem ser realizados sempre antes de qualquer saída ao navegador, ou seja, sempre antes de códigos HTML e funções que exibam dados, como echo, print, print_r etc. Também não pode haver espaços vazios no código, antes da tag &lt;?.</p>
<p>O membro hinom, do iMasters Fóruns, escreveu um excelente tutorial sobre isso, que pode ser visto no link abaixo:<br />
<a href="http://forum.imasters.com.br/index.php?/topic/342563-dicas-para-uso-de-variaveis-de-sessao" onclick="urchinTracker('/outgoing/forum.imasters.com.br/index.php?/topic/342563-dicas-para-uso-de-variaveis-de-sessao&amp;referer=');">http://forum.imasters.com.br/index.php?/topic/342563-dicas-para-uso-de-variaveis-de-sessao</a></p>
<p><a name="undef_func"><br />
<h3>Call to undefined function</h3>
<p></a></p>
<p>Novamente, o erro é claro: foi feita uma chamada a uma função não definida.</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>
beraldo<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>Erro:</p>
<pre>
Fatal error:  Call to undefined function beraldo() in teste.php on line 2
</pre>
<p>Para corrigir, defina a função. Pode ter havido erro de digitação do nome da função ou falta de inclusão do arquivo que a define.</p>
<p><a name="class_notfound"><br />
<h3>Class not found</h3>
<p></a></p>
<p>Ocorre quando o PHP não encontra a classe que se deseja instanciar.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Beraldo<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></div></div>

<p>Erro:</p>
<pre>
Fatal error:  Class 'beraldo' not found in teste.php on line 2
</pre>
<p>Como no erro anterior, a solução é declarar a classe, além de verificar se não houve erro de digitação ou falta de inclusão de arquivo.</p>
<p><a name="undef_method"><br />
<h3>Call to undefined method</h3>
<p></a></p>
<p>Ocorre quando se chama um método inexistente de uma classe.</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>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Beraldo
<span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> darOi<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;oi&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$Beraldo</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Beraldo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$Beraldo</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">darTchau</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Erro:</p>
<pre>
Fatal error:  Call to undefined method Beraldo::darTchau() in teste.php on line 12
</pre>
<p>Deve-se criar o método ou verificar se não houve erro de digitação do nome do método.</p>
<p><a name="call_member_func"><br />
<h3>Call to a member function on a non-object</h3>
<p></a></p>
<p>Isso ocorre quando se chama um método em uma variável que não é uma instância de um objeto.</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: #000088;">$var</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'oi, sou uma string'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$var</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">metodo</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>Erro:</p>
<pre>
Fatal error:  Call to a member function metodo() on a non-object in teste.php on line 3
</pre>
<p>Para solucionar o erro, verifique se não usou a variável errada ou se não modificou o valor original da variável, de forma a ter perdido a instância do objeto.</p>
<p><a name="mysql_result_resource"><br />
<h3>supplied argument is not a valid MySQL result resource</h3>
<p></a></p>
<p>Esse erro ocorre quando uma função espera, como parâmetro, um <em>resource</em> retornado por outra função do MySQL. O mais comum é ocorrer erro na linha onde há a função <code>mysql_fetch_assoc()</code>, <code>mysql_fetch_array()</code> e semlhantes. Isso quer dizer que o parâmetro passado não é um <em>resource</em> retornado por <code>mysql_query()</code>, o que indica que a consulta falhiou e <code>mysql_query()</code> retornou <strong><em>FALSE</em></strong>.</p>
<p>Mensagem de erro:</p>
<pre>
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in ...
</pre>
<p>A solução é corrigir a query executada. Muitas vezes o erro é simples, apenas nome de tabela ou campo errados, ou erro de sintaxe. Para visualizar o erro retornado pelo MySQL, pode-se usar a função <code>mysql_error()</code>. Logo, deve-se executar a consulta desta maneira:</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;">$exec</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$sua_consulta_aqui</span> <span style="color: #009900;">&#41;</span> or <span style="color: #990000;">exit</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">mysql_error</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Caso a consulta falhe, ou seja, <code>mysql_query</code> retorne <strong><em>FALSE</em></strong>, a função <code>exit()</code> finalizará a execução do script, mostrando o erro do MySQL, devido à função <code>mysql_error()</code>. Ler a mensagem de erro ajuda a encontrar o erro na consulta SQL.</p>
<p><em>OBS: Mostrei exemplo usando <strong>MySQL</strong>, mas recomendo fortemente que seja usada a extensão <strong>MySQLi</strong>, que é bem mais completa, além de prover recuersos novos do MySQL 4.1.</em></p>
<p><a name="foreach"><br />
<h3>Invalid argument supplied for foreach()</h3>
<p></a></p>
<p>Esse erro ocorre quando o argumento passado para o <em>loop foreach</em> não é um <em>array</em>.</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: #000088;">$var</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$var</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$k</span> <span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$k</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>Erro:</p>
<pre>
Warning:  Invalid argument supplied for foreach() in teste.php on line 3
</pre>
<p>Como <code>$var</code> é uma <em>string</em>, foi gerado o erro. Para corrigir, basta verificar se o parâmetro está correto ou se ele não foi modificado durante a execução do script, deixando de ser um <em>array</em>.</p>
<p><a name="conclusao"><br />
<h3>Conclusão</h3>
<p></a></p>
<p>As mensagens de erros geralmente são muito claras. Portanto, leia-as atentamente antes de perguntar para alguém ou criar um tópico em um fórum só para isso. Muitas vezes os erros são de fácil correção, bastando ler com cuidado das mensagens de erro.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/as-mensagens-de-erros-mais-comuns-do-php/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Enviando E-Mails com a Classe PHPMailer</title>
		<link>http://www.rberaldo.com.br/blog/enviando-e-mails-com-a-classe-phpmailer/</link>
		<comments>http://www.rberaldo.com.br/blog/enviando-e-mails-com-a-classe-phpmailer/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 23:23:59 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[gmail]]></category>
		<category><![CDATA[mail]]></category>
		<category><![CDATA[phpmailer]]></category>
		<category><![CDATA[smtp]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=339</guid>
		<description><![CDATA[Tutorial mostrando como usar a classe PHPMailer com SMTP externo do GMail, com anexo]]></description>
			<content:encoded><![CDATA[<p>O PHP posusi a <a href="http://php.net/manual/en/function.mail.php" onclick="urchinTracker('/outgoing/php.net/manual/en/function.mail.php?referer=');">função mail</a>, porém ela é simples demais, uma vez que só é possível usar SMTP local, além de ser necessário definir manualmente todos os cabeçalhos da mensagem. Esses cabeçalhos devem ser preenchidos corretamente, uma vez que são usados por servidores de emails como principal forma de identificação de spam. Mensagens com cabeçalhos fracos e incompletos têm alta probabilidade de serem consideradas spam.</p>
<p>A fim de facilitar o envio de e-mails, foi criada a classe <a href="http://phpmailer.worxware.com" title="Link para a página oficial do PHPMailer" onclick="urchinTracker('/outgoing/phpmailer.worxware.com?referer=');">PHPMailer</a>, que possui excelente configuração de cabeçalhos, além de facilitar tarefas meio chatas, como anexar arquivos nas mensagens.</p>
<p><span id="more-339"></span></p>
<p>A classe PHPMailer pode ser baixada em seu <a href="http://phpmailer.worxware.com" title="Link para a página oficial do PHPMailer" onclick="urchinTracker('/outgoing/phpmailer.worxware.com?referer=');">site oficial</a>. O pacote baixado terá, dentre outros arquivos e diretórios, os arquivos <code>class.phpmailer.php</code> e <code>class.smtp.php</code>. O primeiro contém a classe PHPMailer, a qual instanciaremos para o envio da mensagem; o segundo contém a classe para envio de email por SMTP. Esse arquivo é automaticamente inclúido pela classe PHPMailer, caso opte-se por envio via SMTP, ou seja, não é necessário incluir esse arquivo, apenas o <code>class.phpmailer.php</code>.</p>
<p>Vou postar um exemplo simples, com comentário nas principais instruções. Usarei o SMTP do GMail, mas pode ser usado qualquer outro SMTP. Notem que o GMail usa SSL e porta diferente da padrão do SMTP (25).</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
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">require</span> <span style="color: #0000ff;">'phpmailer/class.phpmailer.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$PHPMailer</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> PHPMailer<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// define que será usado SMTP</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">IsSMTP</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// envia email HTML</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isHTML</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// codificação UTF-8, a codificação mais usada recentemente</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Charset</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'UTF-8'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Configurações do SMTP</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">SMTPAuth</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">SMTPSecure</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'ssl'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Host</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'smtp.gmail.com'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Port</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">465</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Username</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'seu_login'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Password</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'sua_senha'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// E-Mail do remetente (deve ser o mesmo de quem fez a autenticação</span>
<span style="color: #666666; font-style: italic;">// nesse caso seu_login@gmail.com)</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">From</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'seu_login@gmail.com'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Nome do rementente</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">FromName</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Seu Nome'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// assunto da mensagem</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Subject</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Teste'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// corpo da mensagem</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Body</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'&lt;p&gt;Mensagem em HTML&lt;/p&gt;'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// corpo da mensagem em modo texto</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">AltBody</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Mensagem em texto'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// adiciona destinatário (pode ser chamado inúmeras vezes)</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">AddAddress</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'meu_amigo@dominio.com'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// adiciona um anexo</span>
<span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">AddAttachment</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'arquivo.pdf'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// verifica se enviou corretamente</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Send</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: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Enviado com sucesso&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;">'Erro do PHPMailer: '</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$PHPMailer</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ErrorInfo</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>É muito fácil mexer com o PHPMailer. Até anexar um arquivo é simples! :)</p>
<p><a href="http://phpmailer.worxware.com" title="Link para a página oficial do PHPMailer" onclick="urchinTracker('/outgoing/phpmailer.worxware.com?referer=');">Site oficial do PHPMailer</a><br />
<a href="http://phpmailer.worxware.com/index.php?pg=properties" title="Propriedades da classe PHPMailer" onclick="urchinTracker('/outgoing/phpmailer.worxware.com/index.php?pg=properties&amp;referer=');">Propriedades da classe PHPMailer</a><br />
<a href="http://phpmailer.worxware.com/index.php?pg=methods" title="Métodos da classe PHPMailer" onclick="urchinTracker('/outgoing/phpmailer.worxware.com/index.php?pg=methods&amp;referer=');">Métodos da classe PHPMailer</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/enviando-e-mails-com-a-classe-phpmailer/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>PHP: Conversão de Datas: formato brasileiro e formato ISO</title>
		<link>http://www.rberaldo.com.br/blog/php-conversao-de-datas-formato-brasileiro-e-formato-iso/</link>
		<comments>http://www.rberaldo.com.br/blog/php-conversao-de-datas-formato-brasileiro-e-formato-iso/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 14:51:33 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Dicas]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[convert]]></category>
		<category><![CDATA[converter]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[eficiente]]></category>
		<category><![CDATA[rapido]]></category>
		<category><![CDATA[tempo]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=302</guid>
		<description><![CDATA[Comparação entre quatro maneiras de se converter datas no formato brasileiro para o formato ISO e vice-versa, a fim de encontrar a mais eficiente]]></description>
			<content:encoded><![CDATA[<p>Uma das principais e mais frequentes dúvidas em fóruns é sobre tratamento de datas. O formato brasileiro é dd/mm/yyy, porém os bancos de dados, por exemplo, trabalham com a data no formato <a href="http://www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/date_and_time_format.htm" title="Link, em inglês, sobre a ISO 8601" onclick="urchinTracker('/outgoing/www.iso.org/iso/support/faqs/faqs_widely_used_standards/widely_used_standards_other/date_and_time_format.htm?referer=');">ISO 8601</a>, ou seja, yyyy-mm-dd.</p>
<p>Face a isso, muitos têm dúvidas em como converter do formato brasileiro para o ISO e vice-versa. É possível fazer isso de várias formas, mas pretendo mostrar aqui as principais delas, comparando o tempo de execução de cada uma, a fim de encontrar a mais eficiente.</p>
<p><span id="more-302"></span></p>
<p>Vamos a quatro exemplos.</p>
<p>O primeiro exemplo usa arrays, com as funções implode, explode, e array_reverse. É talvez o mais usado. Pelo menos é o que mais aparece por aí.</p>
<p>date1.php</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$time</span> <span style="color: #339933;">=</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$date</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'2011-01-15'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #990000;">implode</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'/'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array_reverse</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;">$date</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: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">var_dump</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$time</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>O segundo exemplo usa ER&#8217;s, utilizando a função preg_replace:</p>
<p>date2.php</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$time</span> <span style="color: #339933;">=</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$date</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'2011-01-15'</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'/([0-9]+)-([0-9]+)-([0-9]+)/'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'$3/$2/$1'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$date</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">var_dump</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$time</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>O exemplo 3 usa printf e scanf  (e semelhantes), sem usar variáveis auxiliares, ou seja, fazendo sscanf retornar um array, que é lido por vprintf.</p>
<p>date3.php</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$time</span> <span style="color: #339933;">=</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$date</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'2011-01-15'</span><span style="color: #339933;">;</span>
<span style="color: #990000;">vprintf</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%d</span>/<span style="color: #009933; font-weight: bold;">%d</span>/<span style="color: #009933; font-weight: bold;">%d</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array_reverse</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">sscanf</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$date</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%d</span>-<span style="color: #009933; font-weight: bold;">%d</span>-<span style="color: #009933; font-weight: bold;">%d</span>&quot;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">var_dump</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$time</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>O exemplo 4 usa, novamente, printf e scanf (e semelhantes), mas usa variáveis auxiliares, para evitar o uso de array, da forma como é normalmente usada em linguagens como C e C++.</p>
<p>date4.php</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$time</span> <span style="color: #339933;">=</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$date</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'2011-01-15'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">sscanf</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$date</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%d</span>-<span style="color: #009933; font-weight: bold;">%d</span>-<span style="color: #009933; font-weight: bold;">%d</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$y</span><span style="color: #339933;">,</span> <span style="color: #000088;">$m</span><span style="color: #339933;">,</span> <span style="color: #000088;">$d</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">printf</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;<span style="color: #009933; font-weight: bold;">%d</span>/<span style="color: #009933; font-weight: bold;">%d</span>/<span style="color: #009933; font-weight: bold;">%d</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$d</span><span style="color: #339933;">,</span> <span style="color: #000088;">$m</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;">var_dump</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">microtime</span><span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$time</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Vamos executar os quatro scripts e analisar as saídas deles. Note que aparecerão a data convertida e o tempo de execução de cada um deles. Perceba que o tempo é um float em notação científica.</p>
<p>Saída:</p>
<pre>
date1.php
15/01/2011
float(4.4107437133789E-5)

date2.php
15/01/2011
float(0.0001068115234375)

date3.php
15/01/2011
float(5.1021575927734E-5)

date4.php
15/01/2011
float(3.9815902709961E-5)
</pre>
<p>Aparentemente, o date2.php foi mais rápido, mas, novamente, note a notação científica. Todos os demais estão multiplicados por 10^-5, enquanto o date2.php não está. Logo, ele é o mais lento, não o mais rápido. O mais rápido no teste acima foi o date4.php.</p>
<p>Ou seja, a melhor função para converter datas seria 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> converteData<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$data</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;">strstr</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$data</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'/'</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">// $data está no formato ISO (yyyy-mm-dd) e deve ser convertida</span>
                <span style="color: #666666; font-style: italic;">// para dd/mm/yyyy</span>
                <span style="color: #990000;">sscanf</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$data</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'%d-%d-%d'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$y</span><span style="color: #339933;">,</span> <span style="color: #000088;">$m</span><span style="color: #339933;">,</span> <span style="color: #000088;">$d</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">return</span> <span style="color: #990000;">sprintf</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'%d/%d/%d'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$d</span><span style="color: #339933;">,</span> <span style="color: #000088;">$m</span><span style="color: #339933;">,</span> <span style="color: #000088;">$y</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: #666666; font-style: italic;">// $data está no formato brasileiro e deve ser convertida para ISO</span>
                <span style="color: #990000;">sscanf</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$data</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'%d/%d/%d'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$d</span><span style="color: #339933;">,</span> <span style="color: #000088;">$m</span><span style="color: #339933;">,</span> <span style="color: #000088;">$y</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #b1b100;">return</span> <span style="color: #990000;">sprintf</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'%d-%d-%d'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$y</span><span style="color: #339933;">,</span> <span style="color: #000088;">$m</span><span style="color: #339933;">,</span> <span style="color: #000088;">$d</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <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></pre></div></div>

<p>O tempo de execução pode variar de máquina para máquina. Testei em um AMD Phenon X4 9550. Em alguns outros testes, date1.php ficou muito perto de date4.php, às vezes sendo até mais rápido. Porém na maioria das vezes o date4.php foi mais rápido.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/php-conversao-de-datas-formato-brasileiro-e-formato-iso/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Serialização de Dados</title>
		<link>http://www.rberaldo.com.br/blog/serializacao-de-dados/</link>
		<comments>http://www.rberaldo.com.br/blog/serializacao-de-dados/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 01:34:03 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[arquivo]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[cookie]]></category>
		<category><![CDATA[lista]]></category>
		<category><![CDATA[objeto]]></category>
		<category><![CDATA[pickle]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[serialização]]></category>
		<category><![CDATA[serialize]]></category>
		<category><![CDATA[sessão]]></category>
		<category><![CDATA[socket]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=295</guid>
		<description><![CDATA[A serialização de dados é útil quando é necessário salvar objetos ou arrays em arquivos, cookies, variáveis de sessão ou transmiti-los via sockets.]]></description>
			<content:encoded><![CDATA[<p>Segundo a Wikipédia:</p>
<pre>
Em Ciência da Computação, no contexto de armazenamento e transmissão de dados,
a serialização é o processo de salvar um objeto em um meio de armazenamento
(como um arquivo de computador ou um buffer de memória) ou transmiti-lo por uma
conexão de rede, seja em forma binária ou em formato de texto como o XML. Esta
série de bytes pode ser usada para recriar um objeto com o mesmo estado interno
que o original.
</pre>
<p>Fonte: <a href="http://pt.wikipedia.org/wiki/Serializa%C3%A7%C3%A3o" title="Link para o artigo da Wikipedia sobre Serialização de dados" onclick="urchinTracker('/outgoing/pt.wikipedia.org/wiki/Serializa_C3_A7_C3_A3o?referer=');">http://pt.wikipedia.org/wiki/Serializa%C3%A7%C3%A3o</a></p>
<p>Essa técnica é muito útil quando se deseja salvar dados como arrays ou objetos em arquivos, cookies, sessões ou transmiti-los via sockets, por exemplo.<br />
<span id="more-295"></span></p>
<p>Vou dar um exemplo básico de serialização usando PHP e outro usando Python.</p>
<h3>PHP</h3>
<p>O PHP possui as funções <a href="http://php.net/manual/en/function.serialize.php" title="Link para a documentação da função serialize" onclick="urchinTracker('/outgoing/php.net/manual/en/function.serialize.php?referer=');">serialize</a> e <a href="http://php.net/manual/en/function.unserialize.php" title="Link para a documentação da função unserialize" onclick="urchinTracker('/outgoing/php.net/manual/en/function.unserialize.php?referer=');">unserialize</a>, que funcionam de forma muito simples. Um exemplo prático é suficiente para compreender.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$arr</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'dado 1'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'dado 2'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">var_dump</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$arr</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$serArr</span> <span style="color: #339933;">=</span> <span style="color: #990000;">serialize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$arr</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">var_dump</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$serArr</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$unSerArr</span> <span style="color: #339933;">=</span> <span style="color: #990000;">unserialize</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$serArr</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">var_dump</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$unSerArr</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Saída:</p>
<pre>
array(2) {
  [0]=>
  string(6) "dado 1"
  [1]=>
  string(6) "dado 2"
}
string(40) "a:2:{i:0;s:6:"dado 1";i:1;s:6:"dado 2";}"
array(2) {
  [0]=>
  string(6) "dado 1"
  [1]=>
  string(6) "dado 2"
}
</pre>
<p>Veja que inicialmente o dado é um array. Após a serialização, vira uma string, que pode ser salva em arquivo, cookie, sessão ou transmitida byte a byte via socket. Após ser desserializada, volta a ser um array, da mesma forma como era antes.</p>
<p>Isso vale para qualquer tipo de dado: arrays, objetos, arrays de objetos, objetos com outros objetis intanciados&#8230;</p>
<h3>Python</h3>
<p>O Python possui o módulo <b><a href="http://docs.python.org/library/pickle.html" title="Link para a documentação do módulo pickle do Python" onclick="urchinTracker('/outgoing/docs.python.org/library/pickle.html?referer=');">pickle</a></b>, que permite salvar a serialização direto num arquivo ou atribuí-la a uma variável. O mesmo vale para a desserialização: pode desserializar um dado direto de um arquivo ou a partir de dados de uma variável.</p>
<p>Vou mostrar um exemplo semelhante ao anterior, usando apenas variáveis:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/env python</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">pickle</span><span style="color: #66cc66;">;</span>
&nbsp;
arr = <span style="color: black;">&#91;</span> <span style="color: #483d8b;">'dado 1'</span>, <span style="color: #483d8b;">'dado 2'</span> <span style="color: black;">&#93;</span><span style="color: #66cc66;">;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> arr<span style="color: #66cc66;">;</span>
serArr = <span style="color: #dc143c;">pickle</span>.<span style="color: black;">dumps</span><span style="color: black;">&#40;</span> arr <span style="color: black;">&#41;</span><span style="color: #66cc66;">;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> serArr<span style="color: #66cc66;">;</span>
unSerArr = <span style="color: #dc143c;">pickle</span>.<span style="color: black;">loads</span><span style="color: black;">&#40;</span> serArr <span style="color: black;">&#41;</span><span style="color: #66cc66;">;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> unSerArr<span style="color: #66cc66;">;</span></pre></div></div>

<p>Saída:</p>
<pre>
['dado 1', 'dado 2']
(lp0
S'dado 1'
p1
aS'dado 2'
p2
a.
['dado 1', 'dado 2']
</pre>
<p>Novamente, iniciamos com um array (lista para os mais íntimos ao Python :P ), passando a uma string representando a lista serializada. Ao fim, temos a lista original.</p>
<p>Para usar arquivos, basta usar dump e load, em vez de dumps e loads. Mais exemplos podem ser vistos na documentação do módulo pickle.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/serializacao-de-dados/feed/</wfw:commentRss>
		<slash:comments>0</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>PDML: Gerando PDFs facilmente com PHP</title>
		<link>http://www.rberaldo.com.br/blog/pdml-gerando-pdfs-facilmente-com-php/</link>
		<comments>http://www.rberaldo.com.br/blog/pdml-gerando-pdfs-facilmente-com-php/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 18:51:51 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[Dicas]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[fpdf]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[pdml]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=201</guid>
		<description><![CDATA[PDML, gerador de PDFs de forma simples com PHP, formatação semelhante à de um documento HTML ou XML]]></description>
			<content:encoded><![CDATA[<p>A biblioteca FPDF é muito conhecida e muito utilizada. Porém, conheci esses dias uma biblioteca ainda mais simples de se usar para gerar arquivos PDF com PHP: a PDML, uma ferramenta que possibilita gerar PDFs de uma maneira bem simples e familiar para quem conhece HTML ou XML, uma vez que a formatação do PDML é semelhante à do HTML (ou XML).</p>
<p><span id="more-201"></span></p>
<p>Veja um exemplo, retirado do site oficial:</p>

<div class="wp_syntax"><div 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;">'pdml.php'</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;pdml&gt;
&lt;body&gt;
&lt;font face=&quot;Arial&quot; size=&quot;16pt&quot;&gt;Hello, World&lt;/font&gt;
&lt;/body&gt;
&lt;/pdml&gt;</pre></div></div>

<p>A geração da saída pode ser vista no link abaixo:<br />
<a href="http://www.pdml-pdf.net/demo/index.php?page=create&#038;example=1" target="_blank" onclick="urchinTracker('/outgoing/www.pdml-pdf.net/demo/index.php?page=create_038_example=1&amp;referer=');">http://www.pdml-pdf.net/demo/index.php?page=create&#038;example=1</a></p>
<p>Na documentação oficial há todas as tags que podem ser usadas.</p>
<p>Divirtam-se! =)</p>
<p><a href="http://www.pdml-pdf.net" target="_blank" onclick="urchinTracker('/outgoing/www.pdml-pdf.net?referer=');">Site Oficial do PDML</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/pdml-gerando-pdfs-facilmente-com-php/feed/</wfw:commentRss>
		<slash:comments>1</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>Problemas com codificação: acentos não interpretados</title>
		<link>http://www.rberaldo.com.br/blog/problemas-com-codificacao-acentos-nao-interpretados/</link>
		<comments>http://www.rberaldo.com.br/blog/problemas-com-codificacao-acentos-nao-interpretados/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 12:07:38 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[acentos]]></category>
		<category><![CDATA[Banco de Dados]]></category>
		<category><![CDATA[charset]]></category>
		<category><![CDATA[codificação]]></category>
		<category><![CDATA[collation]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=120</guid>
		<description><![CDATA[Um dúvida muito recorrente em fóruns concerne a erros com acentuação, quando palavras como "atenção" são exibidas como "aten??o". A solução é simples: padronizar as codificações de arquivos, do banco de dados e do HTML.]]></description>
			<content:encoded><![CDATA[<p>Um dúvida muito recorrente em fóruns concerne a erros com acentuação, quando palavras como &#8220;atenção&#8221; são exibidas como &#8220;aten??o&#8221;. A solução é simples: padronizar as codificações de arquivos, do banco de dados e do HTML.</p>
<p><span id="more-120"></span><br />
A melhor codificação a ser usada é a <a title="UTF-8" href="http://en.wikipedia.org/wiki/Utf-8" target="_blank" onclick="urchinTracker('/outgoing/en.wikipedia.org/wiki/Utf-8?referer=');">UTF-8</a>, que suporta diversos idiomas, e tem sido adotada como codificação padrão em diversas aplicações.</p>
<p>E importante manter todas as codificações iguais, ou seja, todas em UTF-8. Para um site, é preciso atentar para as seguintes codificações:</p>
<h3>Codificação do arquivo propriamente dito</h3>
<p>É a codificação do arquivo dentro do sistema operacional. Ela pode ser modificada por meio do seu editor de textos. Por exemplo:</p>
<p><em>Exemplo de alteração de codificação no editor Gedit</em><br />
<a href='http://img194.imageshack.us/i/encodegedit.png/' title="Clique para ampliar" onclick="urchinTracker('/outgoing/img194.imageshack.us/i/encodegedit.png/?referer=');"><img src='http://img194.imageshack.us/img194/3156/encodegedit.png' border='0' alt='Clique para ampliar'/></a><br />
</p>
<p><em>Exemplo de alteração de codificação no editor Eclipse</em><br />
<a href='http://img4.imageshack.us/i/encodeeclipse.png/' title="Clique para ampliar" onclick="urchinTracker('/outgoing/img4.imageshack.us/i/encodeeclipse.png/?referer=');"><img src='http://img4.imageshack.us/img4/9705/encodeeclipse.png' border='0' alt='Clique para ampliar'/></a></p>
<h3>Codificação do HTML</h3>
<p>A codificação do HTML é definida por meio de meta tag ou da função <a title="header()" href="http://www.php.net/manual/pt_BR/function.header.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/function.header.php?referer=');">header()</a>, do PHP.</p>
<p>Definição por meio de meta tag:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;</pre></div></div>

<p>Definição por meio da função header(), do 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: #990000;">header</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'Content-Type: text/html; charset=utf-8'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Codificação do banco de dados e das tabelas</h3>
<p>Se a sua aplicação usa um banco de dados, ele precisa, também, estar na codificação usada &#8211; UTF-8 no nosso caso. Ela é definida quando se criam o banco de dados e as tabelas. Por exemplo, com MySQL, podemos definir as codificação assim:</p>
<p>Codificação do banco de dados:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">DATABASE</span> bancodedados <span style="color: #993333; font-weight: bold;">DEFAULT</span> <span style="color: #993333; font-weight: bold;">CHARACTER</span> <span style="color: #993333; font-weight: bold;">SET</span> utf8 <span style="color: #993333; font-weight: bold;">COLLATE</span> utf8_general_ci;</pre></div></div>

<p>Codificação das tabelas:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> tabela<span style="color: #66cc66;">&#40;</span>
	id <span style="color: #993333; font-weight: bold;">SMALLINT</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">UNSIGNED</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> auto_incre3ment<span style="color: #66cc66;">,</span>
	nome <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">20</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
	sobrenome <span style="color: #993333; font-weight: bold;">VARCHAR</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
	<span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span> <span style="color: #66cc66;">&#40;</span>id<span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">DEFAULT</span> <span style="color: #993333; font-weight: bold;">CHARACTER</span> <span style="color: #993333; font-weight: bold;">SET</span> utf8 <span style="color: #993333; font-weight: bold;">COLLATE</span> utf8_general_ci;</pre></div></div>

<p>Assim, todos os campos do tipo string estarão na codificação utf8.</p>
<h3>Problemas persistentes</h3>
<p>Se você usava codificações diferentes, e, depois, modificou apenas a codificação do banco de dados, as acentuações, provavelmente, continuarão erradas. Não basta apenas mudar a codificação, nesse caso; será necessário passar os dados para outra tabela, que esteja, inicialmente, na codificação correta. É possível fazer essa transferência de dados por meio de apenas uma consulta. Para MySQWL, por exemplo, é possível usar um <a title="INSERT INTO...SELECT" href="http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html" target="_blank" onclick="urchinTracker('/outgoing/dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html?referer=');">INSERT INTO&#8230; SELECT</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/problemas-com-codificacao-acentos-nao-interpretados/feed/</wfw:commentRss>
		<slash:comments>11</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>Trabalhando com a biblioteca cURL</title>
		<link>http://www.rberaldo.com.br/blog/trabalhando-com-a-biblioteca-curl/</link>
		<comments>http://www.rberaldo.com.br/blog/trabalhando-com-a-biblioteca-curl/#comments</comments>
		<pubDate>Fri, 02 Oct 2009 16:29:46 +0000</pubDate>
		<dc:creator>Beraldo</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[bot de busca]]></category>
		<category><![CDATA[cURL]]></category>
		<category><![CDATA[robot]]></category>
		<category><![CDATA[robot de busca]]></category>
		<category><![CDATA[web service]]></category>

		<guid isPermaLink="false">http://www.rberaldo.com.br/blog/?p=75</guid>
		<description><![CDATA[A biblioteca cURL do PHP nos auxilia a buscar informações em outro sites, possibilitando a obtenção de dados remotos, como criação de WEB Services, bots de busca etc. Neste tutorial, são mostradas algumas técnicas e aplicações da cURL.]]></description>
			<content:encoded><![CDATA[<p>A biblioteca <a href="http://www.php.net/manual/pt_BR/book.curl.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/book.curl.php?referer=');">cURL</a> do PHP nos auxilia a buscar informações em outro sites, possibilitando a obtenção de dados remotos, como criação de <em>WEB Services</em>, <em>bots</em> de busca etc.</p>
<p><span id="more-75"></span></p>
<p>Vamos começar com um simples exemplo, acessando o site do Google e exibindo o conteúdo obtido.</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: #666666; font-style: italic;">// página que desejamos acessar</span>
<span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://www.google.com.br'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// iniciamos uma instância do cURL</span>
<span style="color: #000088;">$ch</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// definimos a URL a ser acessada</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_URL<span style="color: #339933;">,</span> <span style="color: #000088;">$pagina</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// executamos a ação</span>
<span style="color: #990000;">curl_exec</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// encerramos a instância do cURL</span>
<span style="color: #990000;">curl_close</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Caso queira, em vez de exibir o conteúdo, retorná-lo a uma variável, para um tratamento de string, por exemplo, basta usar a opção RETURNTRANSFER. O código ficará assim:</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
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://www.google.com.br'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$ch</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_URL<span style="color: #339933;">,</span> <span style="color: #000088;">$pagina</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// define que o conteúdo obtido deve ser retornado em vez de exibido</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_RETURNTRANSFER<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$retorno</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_exec</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_close</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// trocamos a palavra &quot;Google&quot; por &quot;Beraldo&quot;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/google/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Beraldo&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$retorno</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Será  exibido o conteúdo, porém, com a palavra &#8220;Beraldo&#8221; substituindo todas as palavras &#8220;Google&#8221;.</p>
<p>Há diversas opções para usar com a função curl_setopt. Veja a lista completa no <a href="http://www.php.net/manual/pt_BR/function.curl-setopt.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/function.curl-setopt.php?referer=');">link da documentação dessa função</a>.</p>
<p>Por padrão, o cURL não segue redirecionamentos. Por exemplo, se houver um <strong>header(&#8220;Location: url&#8221;);</strong>, o redirecionamento não será feito. Para contornar isso, usamos a opção CURLOPT_FOLLOWLOCATION. Usarei o site www.google.com para testar. Experimente retirar esta última opção inserida e veja que a página em português não e exibida.</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
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://www.google.com'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$ch</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_URL<span style="color: #339933;">,</span> <span style="color: #000088;">$pagina</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_RETURNTRANSFER<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// define que deve-se seguir redirecionamentos</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_FOLLOWLOCATION<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$retorno</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_exec</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_close</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">echo</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/google/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Beraldo&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$retorno</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Os exemplos acima poderiam perfeitamente funcionar com funções de manipulação de arquivos, como file_get_contents. Porém, essas funções não podem executar requisições com método POST. É aí que entra o cURL! :)</p>
<p>A opção CURLOPT_POST define que a requisição será pelo método POST. Para definir os campos da requisição, usaremos CURLOPT_POSTFIELDS. Vamos a 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
14
15
16
17
18
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// campos da requisição POST</span>
<span style="color: #000088;">$postfields</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
						<span style="color: #0000ff;">'nome'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Beraldo'</span><span style="color: #339933;">,</span>
						<span style="color: #0000ff;">'site'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'www.rberaldo.com.br'</span>
					<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// página que receberá a requisição post</span>
<span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://localhost/tmp/curl/post.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$ch</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_URL<span style="color: #339933;">,</span> <span style="color: #000088;">$pagina</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_POST<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_POSTFIELDS<span style="color: #339933;">,</span> <span style="color: #000088;">$postfields</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_exec</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Código do arquivo post.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: #990000;">print_r</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$_POST</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Isso mostrará os campos que definimos no nosso script de cURL.</p>
<p>Podemos usar a opção CURLOPT_HEADER para incluir na saída o cabeçalho da página. Por 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
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// campos da requisição POST</span>
<span style="color: #000088;">$postfields</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
						<span style="color: #0000ff;">'nome'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Beraldo'</span><span style="color: #339933;">,</span>
						<span style="color: #0000ff;">'site'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'www.rberaldo.com.br'</span>
					<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// página que receberá a requisição post</span>
<span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://localhost/tmp/curl/post.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$ch</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_URL<span style="color: #339933;">,</span> <span style="color: #000088;">$pagina</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_POST<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_POSTFIELDS<span style="color: #339933;">,</span> <span style="color: #000088;">$postfields</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// define que o cabeçalho deve ser incluso na saída da requisição</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_HEADER<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_exec</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>É possível, inclusive, enviar arquivos por cURL, via POST. Basta incluir mais um campo e inserir o arroba (@) antes do caminho completo do arquivo. Por 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
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// campos da requisição POST</span>
<span style="color: #000088;">$postfields</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
						<span style="color: #0000ff;">'nome'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Beraldo'</span><span style="color: #339933;">,</span>
						<span style="color: #0000ff;">'site'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'www.rberaldo.com.br'</span><span style="color: #339933;">,</span>
						<span style="color: #0000ff;">'arquivo'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'@/tmp/imagem.jpg'</span>
					<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// página que receberá a requisição post</span>
<span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://localhost/tmp/curl/post.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$ch</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_URL<span style="color: #339933;">,</span> <span style="color: #000088;">$pagina</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_POST<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_POSTFIELDS<span style="color: #339933;">,</span> <span style="color: #000088;">$postfields</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_HEADER<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_exec</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_close</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Se você inserir um <strong>print_r( $_FILES );</strong> no post.php, verá os dados do arquivo enviado. ;)</p>
<p>Unindo as duas últimas opções (POST e HEADER), podemos falar sobre login usando cURL. Sim, é possível, inclusive, fazer login em sites usnado cURL. Afinal, essa biblioteca pode perfeitamente simular um navegador ou um bot de busca.</p>
<p>Primeiro vamos incluir a criação de um cookie no nosso arquivo post.php, deixando-o da seguinte forma:</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: #990000;">setcookie</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;test&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;valor do cookie de teste&quot;</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;">3600</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">print_r</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$_POST</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>E o nosso script de cURL passará a receber o valor do cookie que deve ser salvo 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
20
21
22
23
24
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// campos da requisição POST</span>
<span style="color: #000088;">$postfields</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
						<span style="color: #0000ff;">'nome'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Beraldo'</span><span style="color: #339933;">,</span>
						<span style="color: #0000ff;">'site'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'www.rberaldo.com.br'</span>
					<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// página que receberá a requisição post</span>
<span style="color: #000088;">$pagina</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://localhost/tmp/curl/post.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$ch</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_URL<span style="color: #339933;">,</span> <span style="color: #000088;">$pagina</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_POST<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_POSTFIELDS<span style="color: #339933;">,</span> <span style="color: #000088;">$postfields</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_RETURNTRANSFER<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_HEADER<span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$retorno</span> <span style="color: #339933;">=</span> <span style="color: #990000;">curl_exec</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">curl_close</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">&quot;/Set-Cookie:([^<span style="color: #000099; font-weight: bold;">\n</span>]+)/i&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$retorno</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: #000088;">$cookie</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$matches</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: #b1b100;">echo</span> <span style="color: #000088;">$cookie</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>A variável $cookie conterá o valor do cookie que deve ser salvo no navegador. Para salvar esse cookie, usamos a opção CURLOPT_COOKIE. Tendo esse valor salvo numa variável, basta fazer isto no script que se conecta a uma página que exija esse cookie:</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: #990000;">curl_setopt</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> CURLOPT_COOKIE<span style="color: #339933;">,</span> <span style="color: #000088;">$cookie</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Na documentação das funções cURL (especialmente na da função curl_setopt) é possível encontrar muitas outras funcionalidades para a cURL. É possível definir cabeçalhos de navegador, idioma, usar SSL, proxy e muito mais.</p>
<p>Lista de funções da cURL:<br />
<a href="http://www.php.net/manual/pt_BR/ref.curl.php" target="_blank" onclick="urchinTracker('/outgoing/www.php.net/manual/pt_BR/ref.curl.php?referer=');">http://www.php.net/manual/pt_BR/ref.curl.php</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.rberaldo.com.br/blog/trabalhando-com-a-biblioteca-curl/feed/</wfw:commentRss>
		<slash:comments>4</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>
	</channel>
</rss>

