<?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>Carlos André Ferrari &#187; php</title>
	<atom:link href="http://ferrari.eti.br/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://ferrari.eti.br</link>
	<description>php, python, xhtml, html5, css, javascript, jquery, webstandards, linux, nginx</description>
	<lastBuildDate>Thu, 29 Jul 2010 10:05:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Pegando a temperatura de qualquer cidade</title>
		<link>http://ferrari.eti.br/pegando-a-temperatura-de-qualquer-cidade/</link>
		<comments>http://ferrari.eti.br/pegando-a-temperatura-de-qualquer-cidade/#comments</comments>
		<pubDate>Thu, 29 Jul 2010 09:36:38 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[codigo]]></category>
		<category><![CDATA[scripts]]></category>
		<category><![CDATA[temperatura]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=126</guid>
		<description><![CDATA[Me surgiu um trabalho aqui pelo qual preciso exibir a temperatura atual da cidade, e como estava com insônia decidi brincar um pouco e criar uma solução para isso, fui para o google e pesquisei por &#8220;Previsão do Tempo&#8220;, me surgiram alguns resultados, porém, gostei mais do UOL.
Depois disso foi correr para a criação do [...]]]></description>
			<content:encoded><![CDATA[<p>Me surgiu um trabalho aqui pelo qual preciso exibir a <strong>temperatura</strong> atual da cidade, e como estava com insônia decidi brincar um pouco e criar uma solução para isso, fui para o google e pesquisei por &#8220;<strong>Previsão do Tempo</strong>&#8220;, me surgiram alguns resultados, porém, gostei mais do <a href="http://tempoagora.uol.com.br/previsaodotempo.html/brasil/Palmas-TO/">UOL</a>.</p>
<p>Depois disso foi correr para a criação do script para ler o HTML e retornar um objeto contendo as informações da temperatura no momento, segue o código escrito em <strong>php</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> loadTemp<span style="color: #009900;">&#40;</span><span style="color: #000088;">$cidade</span><span style="color: #339933;">=</span><span style="color: #0000ff;">'Palmas-TO'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// variavel para dados de retorno</span>
	<span style="color: #000088;">$ret</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'url'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;http://tempoagora.uol.com.br/previsaodotempo.html/brasil/<span style="color: #006699; font-weight: bold;">$cidade</span>/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// carrega o html do tempoagora</span>
	<span style="color: #000088;">$html</span> <span style="color: #339933;">=</span> <span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$ret</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'url'</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;">// Pegamos apenas a parte que interessa do html</span>
	<span style="color: #000088;">$iniflag</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'&lt;!-- Insere dados Atuais de AeroPortos ou Est. Meteorologica --&gt;'</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$fimflag</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'&lt;!-- FIM Insere dados Atuais de AeroPortos ou Est. Meteorologica --&gt;'</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$ini</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strrpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$html</span><span style="color: #339933;">,</span> <span style="color: #000088;">$iniflag</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$iniflag</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$fim</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strpos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$html</span><span style="color: #339933;">,</span> <span style="color: #000088;">$fimflag</span><span style="color: #339933;">,</span> <span style="color: #000088;">$ini</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$html</span> <span style="color: #339933;">=</span> <span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$html</span><span style="color: #339933;">,</span> <span style="color: #000088;">$ini</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$fim</span><span style="color: #339933;">-</span><span style="color: #000088;">$ini</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;">// pegamos a url do icone</span>
	<span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'@&lt;img src=&quot;/(imagens/icones/[a-zA-Z\-]+.gif)&quot;@'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$html</span><span style="color: #339933;">,</span> <span style="color: #000088;">$mat</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$ret</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'icone'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'http://tempoagora.uol.com.br/'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$mat</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// Limpa o código html</span>
	<span style="color: #000088;">$content</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strip_tags</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$html</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$content</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'&amp;nbsp;'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">' '</span><span style="color: #339933;">,</span> <span style="color: #000088;">$content</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// quebra o que sobrou em um vetor</span>
	<span style="color: #000088;">$content</span> <span style="color: #339933;">=</span> <span style="color: #990000;">explode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$content</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// limpa espaços e linhas em branco</span>
	<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$content</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$k</span> <span style="color: #339933;">=&gt;</span> <span style="color: #339933;">&amp;</span><span style="color: #000088;">$v</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$v</span> <span style="color: #339933;">=</span> <span style="color: #990000;">trim</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$v</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$v</span><span style="color: #339933;">===</span><span style="color: #0000ff;">''</span><span style="color: #009900;">&#41;</span> <span style="color: #990000;">unset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$content</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$k</span><span style="color: #009900;">&#93;</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;">// pega horário da verificação</span>
	<span style="color: #000088;">$lin</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_shift</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$content</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #990000;">preg_match</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'@[0-9]{1,2}:[0-9]{1,2}@'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$lin</span><span style="color: #339933;">,</span> <span style="color: #000088;">$mat</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$ret</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'verificado'</span><span style="color: #009900;">&#93;</span>  <span style="color: #339933;">=</span> <span style="color: #000088;">$mat</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// pega insidência de nuvens</span>
	<span style="color: #000088;">$ret</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'nuvens'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_shift</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$content</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// define nomes melhores para as próximas propriedades</span>
	<span style="color: #000088;">$keys</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'temperatura'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'sensacao'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'vento'</span><span style="color: #339933;">,</span> 
			<span style="color: #0000ff;">'pressao'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'umidade'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'visibilidade'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// reseta as chaves do vetor</span>
	<span style="color: #000088;">$content</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array_unique</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$content</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// percorre chaves impares e aplica as propriedades definidas acima</span>
	<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$x</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> <span style="color: #000088;">$x</span><span style="color: #339933;">&lt;=</span><span style="color: #cc66cc;">11</span><span style="color: #339933;">;</span> <span style="color: #000088;">$x</span><span style="color: #339933;">=</span><span style="color: #000088;">$x</span><span style="color: #339933;">+</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$ret</span><span style="color: #009900;">&#91;</span><span style="color: #990000;">array_shift</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$keys</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$content</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$x</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">// retorna os dados como um objeto</span>
	<span style="color: #b1b100;">return</span> <span style="color: #009900;">&#40;</span>object<span style="color: #009900;">&#41;</span><span style="color: #000088;">$ret</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Analisando o site deles, notei que a <strong>temperatura</strong> é atualizada de hora em hora, então a melhor forma de utilizar essa solução é utilizando o <strong>crontab</strong>, que executa a cada hora, eu escolhi executar no quinto minuto de cada hora cheia (5:05, 6:05, etc).</p>
<p>segue o código <strong>php</strong> que o <strong>crontab</strong> executa:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">require</span> <span style="color: #0000ff;">'loadTemp.php'</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// define nome do arquivo de cache</span>
<span style="color: #000088;">$cache_file</span> <span style="color: #339933;">=</span> <span style="color: #990000;">sys_get_temp_dir</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/temp'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// carrega a temperatura</span>
<span style="color: #000088;">$temp</span> <span style="color: #339933;">=</span> loadTemp<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;">// salva em cache</span>
<span style="color: #990000;">file_put_contents</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$cache_file</span><span style="color: #339933;">,</span> <span style="color: #990000;">serialize</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$temp</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>E para exibir no sistema eu fiz uma funçãozinha:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> temp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$cache_file</span> <span style="color: #339933;">=</span> <span style="color: #990000;">sys_get_temp_dir</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/temp'</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">// se o cache existe, retorna o objeto</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">file_exists</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$cache_file</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> 
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">unserialize</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$cache_file</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;">// senão cria o cache e retorna =)</span>
	<span style="color: #000088;">$temp</span> <span style="color: #339933;">=</span> loadTemp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #990000;">file_put_contents</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$cache_file</span><span style="color: #339933;">,</span> <span style="color: #990000;">serialize</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$temp</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$temp</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>depois, no local específico, ficou algo mais ou menos assim:</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;">$temp</span> <span style="color: #339933;">=</span> temp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;img src=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$temp</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">icone</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot; alt=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$temp</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">nuvens</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot; /&gt;
&lt;span&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$temp</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">temperatura</span> <span style="color: #000000; font-weight: bold;">?&gt;</span> (&lt;a rel=&quot;external&quot; href=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$temp</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">url</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot;&gt;saiba mais&lt;/a&gt;)&lt;/span&gt;</pre></div></div>

<p>Minha forma de pagar por esse uso é manter um link para o <a href="http://tempoagora.uol.com.br/">Tempoagora</a>, o que é bastante interessante, pois meu visitante pode querer obter mais informações</p>
<p>É isso ai, abraço a todos</p>
]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/pegando-a-temperatura-de-qualquer-cidade/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Classe, WebService e RSS para rastreamento de encomendas nos Correios em PHP</title>
		<link>http://ferrari.eti.br/classe-api-webservice-para-rastreamento-de-encomendas-nos-correios-em-php/</link>
		<comments>http://ferrari.eti.br/classe-api-webservice-para-rastreamento-de-encomendas-nos-correios-em-php/#comments</comments>
		<pubDate>Sat, 10 Apr 2010 10:25:32 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[github]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[classes]]></category>
		<category><![CDATA[opensource]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=117</guid>
		<description><![CDATA[Olá, depois de meses sem escrever estou voltando com uma classe muito útil e simples que nunca vi em lugar nenhum. É uma classe para rastrear encomendas nos correios que eu escrevi em PHP, que retorna um vetor com cada modificação de status lá.
Vamos direto ao ponto, confira o exemplo:
http://ferrari.eti.br/correios/samples/class.php
E para deixar a brincadeira mais [...]]]></description>
			<content:encoded><![CDATA[<p>Olá, depois de meses sem escrever estou voltando com uma <strong>classe</strong> muito útil e simples que nunca vi em lugar nenhum. É uma classe para rastrear encomendas nos <strong>correios</strong> que eu escrevi em <strong>PHP</strong>, que retorna um vetor com cada modificação de status lá.</p>
<p>Vamos direto ao ponto, confira o exemplo:</p>
<p><a href="http://ferrari.eti.br/correios/samples/class.php">http://ferrari.eti.br/correios/samples/class.php</a></p>
<p>E para deixar a brincadeira mais divertida, fiz também um <strong>webservice</strong> com suporte a <strong>Json</strong> (padrão), <strong>phpserialize</strong>, <strong>XML</strong> e um modo dump, para visualização:</p>
<p><a href="http://ferrari.eti.br/correios/webservice/?q=PB151832535BR">http://ferrari.eti.br/correios/webservice/?q=PB151832535BR</a><br />
<a href="http://ferrari.eti.br/correios/webservice/?q=PB151832535BR&amp;f=dump">http://ferrari.eti.br/correios/webservice/?q=PB151832535BR&amp;f=dump</a><br />
<a href="http://ferrari.eti.br/correios/webservice/?q=PB151832535BR&amp;f=serial">http://ferrari.eti.br/correios/webservice/?q=PB151832535BR&amp;f=serial</a><br />
<a href="http://ferrari.eti.br/correios/webservice/?q=PB151832535BR&amp;f=xml">http://ferrari.eti.br/correios/webservice/?q=PB151832535BR&amp;f=xml</a><br />
e claro, para quem usa <strong>Ajax</strong>:<br />
<a href="http://ferrari.eti.br/correios/webservice/?q=PB151832535BR&amp;callback=minhaFuncJs">http://ferrari.eti.br/correios/webservice/?q=PB151832535BR&amp;callback=minhaFuncJs</a></p>
<p>Disponibilizei tanto a classe quanto o código do webservice (que tem suporte a <strong>caching</strong>!) &#8220;de grátis&#8221; e com licença BSD no <strong>github</strong>:</p>
<p><a href="http://github.com/caferrari/correios/">http://github.com/caferrari/correios/</a></p>
<p><strong>*UPDATE* </strong>Adicionado um gerador de RSS, assim é possível usar o proprio agregador para fazer o tracking!<strong></strong></p>
<p><a href="http://ferrari.eti.br/correios/rss/?PB151832535BR">http://ferrari.eti.br/correios/rss/?PB151832535BR</a></p>
<p>e em homenagem aos atendentes de telemarketing: Estarei esperando forks e colaborações para a classe, além de comentários!.</p>
<p>Até a próxima.</p>
]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/classe-api-webservice-para-rastreamento-de-encomendas-nos-correios-em-php/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>PHP 5.3, PHP-FPM, XCache, Nginx no Debian Lenny &#8211; Performance extrema</title>
		<link>http://ferrari.eti.br/php-5-3-php-fpm-xcache-nginx-no-debian-lenny-performance-extrema/</link>
		<comments>http://ferrari.eti.br/php-5-3-php-fpm-xcache-nginx-no-debian-lenny-performance-extrema/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 14:36:08 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[git]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[webserver]]></category>
		<category><![CDATA[debian]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[nginx]]></category>
		<category><![CDATA[php-fpm]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[xcache]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=112</guid>
		<description><![CDATA[Neste post vou exemplificar os passos para configurar um Webserver que consome poucos recursos e é extremamente rápido no Debian Lenny.
PHP-FPM: é um gerenciador de processos CGI do php, similar ao Phpcgi, porém com várias vantagens como:

Gerenciador de Processos muito eficiente, com capacidade de parar e iniciar seus deamons caso necessário
Possibilidade de Iniciar processos com [...]]]></description>
			<content:encoded><![CDATA[<p>Neste post vou exemplificar os passos para configurar um Webserver que consome poucos recursos e é extremamente rápido no <a href="http://www.debian.org/">Debian Lenny</a>.</p>
<p><a href="http://php-fpm.org/">PHP-FPM</a>: é um gerenciador de processos CGI do php, similar ao Phpcgi, porém com várias vantagens como:</p>
<ul>
<li>Gerenciador de Processos muito eficiente, com capacidade de parar e iniciar seus <a href="http://en.wikipedia.org/wiki/Daemon">deamons</a> caso necessário</li>
<li>Possibilidade de Iniciar processos com usuários diferentes e com arquivos php.ini diferentes</li>
<li>Uploads otimizados</li>
<li>Capacidade de reinicializar processos caso ocorra algum problema</li>
<li>Escalabilidade de processos, ele pode criar mais processos de acordo com a demanda</li>
<li>e muito mais.</li>
</ul>
<p><a href="http://xcache.lighttpd.net/">XCache</a>: é um gerenciador de cache, que armazena os scripts php em <a href="http://en.wikipedia.org/wiki/Opcode">opcode</a> para uso futuro, é extremamente rápido e muito usado no mundo em servidores com alta demanda.</p>
<p><a href="http://nginx.org">Nginx</a>: Conheci este webserver lendo o <a href="http://www.boo-box.com/blog/br/2009/nova-infraestrutura-de-servidores-web-do-sistema-boo-box/">blog da boo-box</a>, ele é um Servidor web e proxy reverso extremamente veloz e que vem ganhando mercado nos últimos meses devido a sua facilidade de uso e capacidade de carga.</p>
<p style="text-align: center;"><a href="http://royal.pingdom.com/2010/01/22/internet-2009-in-numbers/"><img class="aligncenter" title="Market Share de navegadores no final de 2009" src="http://farm5.static.flickr.com/4022/4295546152_b8e094e8cc_o.png" alt="Market Share de navegadores no final de 2009" width="580" height="300" /></a></p>
<p>Para agilizar a configuração, vamos usar alguns pacotes (php5.3, php-fpm) pré compilados e mantidos <a href="http://www.dotdeb.org/">www.dotdeb.org.</a> os testes que eu realzei usando estes pacotes tiveram um ganho de performance enorme.</p>
<h3>Instalação:</h3>
<p>Vamos começar adicionado os repositórios do dotdeb no /etc/apt/sources.list:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">deb http:<span style="color: #000000; font-weight: bold;">//</span>php53.dotdeb.org stable all
deb-src http:<span style="color: #000000; font-weight: bold;">//</span>php53.dotdeb.org stable all</pre></div></div>

<p>Vamos instalar os pacotes e algumas dependências para o nginx:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">aptitude</span> update
<span style="color: #c20cb9; font-weight: bold;">aptitude</span> <span style="color: #c20cb9; font-weight: bold;">install</span> php5-fpm php5-xcache php5-gd php5-curl \
php5-mysql php5-pgsql libssl-dev libpcre3-dev build-essential <span style="color: #660033;">-y</span></pre></div></div>

<p>Agora temos o php instalado, vamos compilar o nginx:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span>
<span style="color: #c20cb9; font-weight: bold;">mkdir</span> src
<span style="color: #7a0874; font-weight: bold;">cd</span> src
<span style="color: #c20cb9; font-weight: bold;">wget</span> http:<span style="color: #000000; font-weight: bold;">//</span>nginx.org<span style="color: #000000; font-weight: bold;">/</span>download<span style="color: #000000; font-weight: bold;">/</span>nginx-0.7.64.tar.gz
<span style="color: #c20cb9; font-weight: bold;">tar</span> <span style="color: #660033;">-zxvf</span> nginx-0.7.64.tar.gz
<span style="color: #7a0874; font-weight: bold;">cd</span> nginx-0.7.64
.<span style="color: #000000; font-weight: bold;">/</span>configure <span style="color: #660033;">--prefix</span>=<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>nginx <span style="color: #660033;">--user</span>=www-data <span style="color: #660033;">--group</span>=www-data \
    --without-mail_pop3_module --without-mail_imap_module \
    --without-mail_smtp_module --with-http_stub_status_module \
    --with-http_ssl_module <span style="color: #660033;">--http-log-path</span>=<span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>log<span style="color: #000000; font-weight: bold;">/</span>nginx<span style="color: #000000; font-weight: bold;">/</span>access.log \
    <span style="color: #660033;">--conf-path</span>=<span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>nginx<span style="color: #000000; font-weight: bold;">/</span>nginx.conf  <span style="color: #660033;">--pid-path</span>=<span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span>nginx.pid
<span style="color: #c20cb9; font-weight: bold;">make</span>
<span style="color: #c20cb9; font-weight: bold;">make</span> <span style="color: #c20cb9; font-weight: bold;">install</span></pre></div></div>

<p>Se tudo ocorreu bem, você já tem o nginx instalado, vamos apenas coloca-lo para inicializar automáticamente, crie o arquivo /etc/init.d/nginx e coloque o conteúdo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#! /bin/sh</span>
&nbsp;
<span style="color: #666666; font-style: italic;">### BEGIN INIT INFO</span>
<span style="color: #666666; font-style: italic;"># Provides:          nginx</span>
<span style="color: #666666; font-style: italic;"># Required-Start:    $all</span>
<span style="color: #666666; font-style: italic;"># Required-Stop:     $all</span>
<span style="color: #666666; font-style: italic;"># Default-Start:     2 3 4 5</span>
<span style="color: #666666; font-style: italic;"># Default-Stop:      0 1 6</span>
<span style="color: #666666; font-style: italic;"># Short-Description: starts the nginx web server</span>
<span style="color: #666666; font-style: italic;"># Description:       starts nginx using start-stop-daemon</span>
<span style="color: #666666; font-style: italic;">### END INIT INFO</span>
&nbsp;
<span style="color: #007800;">PATH</span>=<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>sbin:<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>sbin:<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>sbin:<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin:<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span>
<span style="color: #007800;">DAEMON</span>=<span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>local<span style="color: #000000; font-weight: bold;">/</span>nginx<span style="color: #000000; font-weight: bold;">/</span>sbin<span style="color: #000000; font-weight: bold;">/</span>nginx
<span style="color: #007800;">NAME</span>=nginx
<span style="color: #007800;">DESC</span>=nginx
&nbsp;
<span style="color: #7a0874; font-weight: bold;">test</span> <span style="color: #660033;">-x</span> <span style="color: #007800;">$DAEMON</span> <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #000000;">0</span>
&nbsp;
<span style="color: #666666; font-style: italic;"># Include nginx defaults if available</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #660033;">-f</span> <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>default<span style="color: #000000; font-weight: bold;">/</span>nginx <span style="color: #7a0874; font-weight: bold;">&#93;</span> ; <span style="color: #000000; font-weight: bold;">then</span>
        . <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>default<span style="color: #000000; font-weight: bold;">/</span>nginx
<span style="color: #000000; font-weight: bold;">fi</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">set</span> <span style="color: #660033;">-e</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">case</span> <span style="color: #ff0000;">&quot;$1&quot;</span> <span style="color: #000000; font-weight: bold;">in</span>
  start<span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-n</span> <span style="color: #ff0000;">&quot;Starting <span style="color: #007800;">$DESC</span>: &quot;</span>
        start-stop-daemon <span style="color: #660033;">--start</span> <span style="color: #660033;">--quiet</span> <span style="color: #660033;">--pidfile</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span><span style="color: #007800;">$NAME</span>.pid \
                <span style="color: #660033;">--exec</span> <span style="color: #007800;">$DAEMON</span> <span style="color: #660033;">--</span> <span style="color: #007800;">$DAEMON_OPTS</span> <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$NAME</span>.&quot;</span>
        <span style="color: #000000; font-weight: bold;">;;</span>
  stop<span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-n</span> <span style="color: #ff0000;">&quot;Stopping <span style="color: #007800;">$DESC</span>: &quot;</span>
        start-stop-daemon <span style="color: #660033;">--stop</span> <span style="color: #660033;">--quiet</span> <span style="color: #660033;">--pidfile</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span><span style="color: #007800;">$NAME</span>.pid \
                <span style="color: #660033;">--exec</span> <span style="color: #007800;">$DAEMON</span> <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$NAME</span>.&quot;</span>
        <span style="color: #000000; font-weight: bold;">;;</span>
  restart<span style="color: #000000; font-weight: bold;">|</span>force-reload<span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-n</span> <span style="color: #ff0000;">&quot;Restarting <span style="color: #007800;">$DESC</span>: &quot;</span>
        start-stop-daemon <span style="color: #660033;">--stop</span> <span style="color: #660033;">--quiet</span> <span style="color: #660033;">--pidfile</span> \
                <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span><span style="color: #007800;">$NAME</span>.pid <span style="color: #660033;">--exec</span> <span style="color: #007800;">$DAEMON</span> <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
        <span style="color: #c20cb9; font-weight: bold;">sleep</span> <span style="color: #000000;">1</span>
        start-stop-daemon <span style="color: #660033;">--start</span> <span style="color: #660033;">--quiet</span> <span style="color: #660033;">--pidfile</span> \
                <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span><span style="color: #007800;">$NAME</span>.pid <span style="color: #660033;">--exec</span> <span style="color: #007800;">$DAEMON</span> <span style="color: #660033;">--</span> <span style="color: #007800;">$DAEMON_OPTS</span> <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$NAME</span>.&quot;</span>
        <span style="color: #000000; font-weight: bold;">;;</span>
  reload<span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-n</span> <span style="color: #ff0000;">&quot;Reloading <span style="color: #007800;">$DESC</span> configuration: &quot;</span>
        start-stop-daemon <span style="color: #660033;">--stop</span> <span style="color: #660033;">--signal</span> HUP <span style="color: #660033;">--quiet</span> <span style="color: #660033;">--pidfile</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span><span style="color: #007800;">$NAME</span>.pid \
            <span style="color: #660033;">--exec</span> <span style="color: #007800;">$DAEMON</span> <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$NAME</span>.&quot;</span>
        <span style="color: #000000; font-weight: bold;">;;</span>
  configtest<span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #660033;">-n</span> <span style="color: #ff0000;">&quot;Testing <span style="color: #007800;">$DESC</span> configuration: &quot;</span>
        <span style="color: #000000; font-weight: bold;">if</span> nginx <span style="color: #660033;">-t</span> <span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>null <span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">1</span>
        <span style="color: #000000; font-weight: bold;">then</span>
          <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;<span style="color: #007800;">$NAME</span>.&quot;</span>
        <span style="color: #000000; font-weight: bold;">else</span>
          <span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #007800;">$?</span>
        <span style="color: #000000; font-weight: bold;">fi</span>
        <span style="color: #000000; font-weight: bold;">;;</span>
  <span style="color: #000000; font-weight: bold;">*</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
        <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #ff0000;">&quot;Usage: <span style="color: #007800;">$NAME</span> {start|stop|restart|reload|force-reload|configtest}&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">2</span>
        <span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #000000;">1</span>
        <span style="color: #000000; font-weight: bold;">;;</span>
<span style="color: #000000; font-weight: bold;">esac</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #000000;">0</span></pre></div></div>

<p>depois vamos torna-lo executável e atualizar o rc.d:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">chmod</span> +x <span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>init.d<span style="color: #000000; font-weight: bold;">/</span>nginx
update-rc.d nginx defaults</pre></div></div>

<p>Com isso o processo de instalação está concluído, vamos configurar!</p>
<h3>Configuração do XCache</h3>
<p>Coloque a seguinte configuração no arquivo /etc/php5/fpm/conf.d/xcache.ini:</p>

<div class="wp_syntax"><div class="code"><pre class="ini" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">; configuration for php xcache module</span>
<span style="color: #000099;">extension</span><span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">xcache.so</span>
&nbsp;
<span style="color: #000066; font-weight:bold;"><span style="">&#91;</span>xcache.admin<span style="">&#93;</span></span>
xcache.admin.user <span style="color: #000066; font-weight:bold;">=</span> <span style="color: #933;">&quot;secom&quot;</span>
<span style="color: #666666; font-style: italic;">; xcache.admin.pass = md5($your_password)</span>
xcache.admin.pass <span style="color: #000066; font-weight:bold;">=</span> <span style="color: #933;">&quot;&quot;</span>
<span style="color: #000066; font-weight:bold;"><span style="">&#91;</span>xcache<span style="">&#93;</span></span>
<span style="color: #666666; font-style: italic;">; ini only settings, all the values here is default unless explained</span>
<span style="color: #666666; font-style: italic;">; select low level shm/allocator scheme implemenation</span>
xcache.shm_scheme <span style="color: #000066; font-weight:bold;">=</span>        <span style="color: #933;">&quot;mmap&quot;</span>
<span style="color: #666666; font-style: italic;">; to disable: xcache.size=0</span>
<span style="color: #666666; font-style: italic;">; to enable : xcache.size=64M etc (any size &gt; 0) and your system mmap allows</span>
xcache.size  <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">                64M</span>
<span style="color: #666666; font-style: italic;">; set to cpu count (cat /proc/cpuinfo |grep -c processor)</span>
xcache.count <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">                 1</span>
<span style="color: #666666; font-style: italic;">; just a hash hints, you can always store count(items) &gt; slots</span>
xcache.slots <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">                8K</span>
<span style="color: #666666; font-style: italic;">; ttl of the cache item, 0=forever</span>
xcache.ttl   <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">                 0</span>
<span style="color: #666666; font-style: italic;">; interval of gc scanning expired items, 0=no scan, other values is in seconds</span>
xcache.gc_interval <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">           0</span>
<span style="color: #666666; font-style: italic;">; same as aboves but for variable cache</span>
xcache.var_size  <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">            64M</span>
xcache.var_count <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">             1</span>
xcache.var_slots <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">            8K</span>
<span style="color: #666666; font-style: italic;">; default ttl</span>
xcache.var_ttl   <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">             0</span>
xcache.var_maxttl   <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">          0</span>
xcache.var_gc_interval <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">     300</span>
xcache.test <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">                Off</span>
<span style="color: #666666; font-style: italic;">; N/A for /dev/zero</span>
xcache.readonly_protection <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;"> Off</span>
<span style="color: #666666; font-style: italic;">; for *nix, xcache.mmap_path is a file path, not directory.</span>
<span style="color: #666666; font-style: italic;">; Use something like &quot;/tmp/xcache&quot; if you want to turn on ReadonlyProtection</span>
<span style="color: #666666; font-style: italic;">; 2 group of php won't share the same /tmp/xcache</span>
<span style="color: #666666; font-style: italic;">; for win32, xcache.mmap_path=anonymous map name, not file path</span>
xcache.mmap_path <span style="color: #000066; font-weight:bold;">=</span>    <span style="color: #933;">&quot;/dev/zero&quot;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">; leave it blank(disabled) or &quot;/tmp/phpcore/&quot;</span>
<span style="color: #666666; font-style: italic;">; make sure it's writable by php (without checking open_basedir)</span>
xcache.coredump_directory <span style="color: #000066; font-weight:bold;">=</span>   <span style="color: #933;">&quot;&quot;</span>
<span style="color: #666666; font-style: italic;">; per request settings</span>
xcache.cacher <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">               On</span>
xcache.stat   <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">               On</span>
xcache.optimizer <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">            On</span>
<span style="color: #000066; font-weight:bold;"><span style="">&#91;</span>xcache.coverager<span style="">&#93;</span></span>
<span style="color: #666666; font-style: italic;">; per request settings</span>
<span style="color: #666666; font-style: italic;">; enable coverage data collecting for xcache.coveragedump_directory and xcache_coverager_start/stop/get/clean() functions (will hurt executing performance)</span>
xcache.coverager <span style="color: #000066; font-weight:bold;">=</span><span style="color: #660066;">          Off</span>
<span style="color: #666666; font-style: italic;">; ini only settings</span>
<span style="color: #666666; font-style: italic;">; make sure it's readable (care open_basedir) by coverage viewer script</span>
<span style="color: #666666; font-style: italic;">; requires xcache.coverager=On</span>
xcache.coveragedump_directory <span style="color: #000066; font-weight:bold;">=</span> <span style="color: #933;">&quot;&quot;</span></pre></div></div>

<h3>Configuração do Nginx</h3>
<p>Edite o arquivo em /etc/nginx/nginx.conf:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">user  www-data;
&nbsp;
<span style="color: #666666; font-style: italic;">#Coloque quantos processos simultaneos, o ideal é um para cada nucleo do sistema:</span>
worker_processes  <span style="color: #000000;">4</span>;
&nbsp;
error_log  <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>log<span style="color: #000000; font-weight: bold;">/</span>nginx<span style="color: #000000; font-weight: bold;">/</span>error.log;
&nbsp;
events <span style="color: #7a0874; font-weight: bold;">&#123;</span>
    <span style="color: #666666; font-style: italic;"># numero de conexões simultaneas por worker</span>
    worker_connections  <span style="color: #000000;">1024</span>;
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
http <span style="color: #7a0874; font-weight: bold;">&#123;</span>
    include       mime.types;
    default_type  application<span style="color: #000000; font-weight: bold;">/</span>octet-stream;
&nbsp;
    access_log  <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>log<span style="color: #000000; font-weight: bold;">/</span>nginx<span style="color: #000000; font-weight: bold;">/</span>access.log;
    sendfile        on;
    <span style="color: #666666; font-style: italic;"># isso é interessante, dá um ganho enorme na navegação, e o nginx aguenta tranquilamente</span>
    keepalive_timeout  <span style="color: #000000;">60</span>;
    tcp_nodelay        on;
&nbsp;
    <span style="color: #666666; font-style: italic;">## Compressão</span>
    <span style="color: #c20cb9; font-weight: bold;">gzip</span> on;
    gzip_http_version <span style="color: #000000;">1.0</span>;
    gzip_comp_level <span style="color: #000000;">2</span>;
    gzip_proxied any;
    gzip_min_length  <span style="color: #000000;">1100</span>;
    gzip_buffers <span style="color: #000000;">16</span> 8k;
    <span style="color: #666666; font-style: italic;"># mime types para zipar e adicionar header de cache</span>
    gzip_types text<span style="color: #000000; font-weight: bold;">/</span>plain text<span style="color: #000000; font-weight: bold;">/</span>css application<span style="color: #000000; font-weight: bold;">/</span>x-javascript text<span style="color: #000000; font-weight: bold;">/</span>xml application<span style="color: #000000; font-weight: bold;">/</span>xml application<span style="color: #000000; font-weight: bold;">/</span>xml+rss text<span style="color: #000000; font-weight: bold;">/</span>javascript image<span style="color: #000000; font-weight: bold;">/</span>gif image<span style="color: #000000; font-weight: bold;">/</span>jpeg image<span style="color: #000000; font-weight: bold;">/</span>png;
    <span style="color: #666666; font-style: italic;"># Desabilita compressão em algumas versões do IE6</span>
    gzip_disable <span style="color: #ff0000;">&quot;MSIE [1-6].(?!.*SV1)&quot;</span>;
    <span style="color: #666666; font-style: italic;"># Impede que servidores proxy mandem versões em gzip do arquivo para os IE6</span>
    gzip_vary on;
&nbsp;
    server <span style="color: #7a0874; font-weight: bold;">&#123;</span>
	root  <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>www<span style="color: #000000; font-weight: bold;">/</span>;
	server_name     localhost;
	listen          <span style="color: #000000;">80</span>;
	location <span style="color: #000000; font-weight: bold;">/</span> <span style="color: #7a0874; font-weight: bold;">&#123;</span>
		index  index.php index.html index.htm;
	<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">#error_page  404  /404.html;</span>
	<span style="color: #666666; font-style: italic;"># redirect server error pages to the static page /50x.html</span>
	error_page   <span style="color: #000000;">500</span> <span style="color: #000000;">502</span> <span style="color: #000000;">503</span> <span style="color: #000000;">504</span>  <span style="color: #000000; font-weight: bold;">/</span>50x.html;
	location = <span style="color: #000000; font-weight: bold;">/</span>50x.html <span style="color: #7a0874; font-weight: bold;">&#123;</span>
		root   <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>www<span style="color: #000000; font-weight: bold;">/</span>nginx-default;
	<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;"># Joga requisições para arquivos .php para o php-fpm</span>
	location ~ \.php$ <span style="color: #7a0874; font-weight: bold;">&#123;</span>
		fastcgi_pass   127.0.0.1:<span style="color: #000000;">9000</span>;
		fastcgi_index  index.php;
		include fastcgi_params;
        	fastcgi_param SCRIPT_FILENAME <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>www<span style="color: #000000; font-weight: bold;">/</span><span style="color: #007800;">$fastcgi_script_name</span>;
        	fastcgi_param SERVER_NAME <span style="color: #007800;">$http_host</span>;
        	fastcgi_ignore_client_abort on;
	<span style="color: #7a0874; font-weight: bold;">&#125;</span>
    <span style="color: #7a0874; font-weight: bold;">&#125;</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

<h3>Configuração do php-fpm</h3>
<p>Edite o arquivo: /etc/php5/fpm/php5-fpm.conf e faça os ajustes que você achar interessante, aqui eu só aumento os max_childrens (Numero de clientes CGI) de 5 para 50, esta configuração depende do seu hardware.</p>
<h3>Configuração do Logrotate</h3>
<p>Vamos configurar agora o logrotate para não enchermos os discos com logs do nginx, edite o arquivo /etc/logrotate.d/nginx:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>log<span style="color: #000000; font-weight: bold;">/</span>nginx<span style="color: #000000; font-weight: bold;">/*</span>.log <span style="color: #7a0874; font-weight: bold;">&#123;</span>
        daily
        missingok
        rotate <span style="color: #000000;">7</span>
        compress
        delaycompress
        notifempty
        create <span style="color: #000000;">640</span> root adm
        sharedscripts
        postrotate
                <span style="color: #7a0874; font-weight: bold;">&#91;</span> <span style="color: #000000; font-weight: bold;">!</span> <span style="color: #660033;">-f</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span>nginx.pid <span style="color: #7a0874; font-weight: bold;">&#93;</span> <span style="color: #000000; font-weight: bold;">||</span> <span style="color: #c20cb9; font-weight: bold;">kill</span> <span style="color: #660033;">-USR1</span> <span style="color: #000000; font-weight: bold;">`</span><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>run<span style="color: #000000; font-weight: bold;">/</span>nginx.p$
        endscript
<span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

<h3>Finalizando</h3>
<p>Agora que está tudo configurado, vamos reinicalizar os serviços:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>init.d<span style="color: #000000; font-weight: bold;">/</span>php5-fpm restart
<span style="color: #000000; font-weight: bold;">/</span>etc<span style="color: #000000; font-weight: bold;">/</span>init.d<span style="color: #000000; font-weight: bold;">/</span>nginx restart</pre></div></div>

<p>crie um arquivo /var/www/index.php e vamos testar o php:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">&nbsp;
e acesse<span style="color: #339933;">:</span> http<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">//ip_do_servidor/</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/php-5-3-php-fpm-xcache-nginx-no-debian-lenny-performance-extrema/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>nginx &#8211; webserver, proxy reverso e perfeito!</title>
		<link>http://ferrari.eti.br/nginx-webserver-proxy-reverso-e-perfeito/</link>
		<comments>http://ferrari.eti.br/nginx-webserver-proxy-reverso-e-perfeito/#comments</comments>
		<pubDate>Thu, 15 Oct 2009 13:00:25 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[nginx]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[proxy]]></category>
		<category><![CDATA[webserver]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=85</guid>
		<description><![CDATA[Nosso departamento é responsável por manter a identidade visual dos sites do Governo do Estado e ainda fazemos os sites dos orgãos que não possuem um.
No trabalho sempre tivemos um constante problema para hospedar nossos sites: hardware!. Contamos hoje com dois incríveis servidores IBM Pentium4 3Ghz com 2gb de memória e HDs scsi, um para [...]]]></description>
			<content:encoded><![CDATA[<p>Nosso <a href="http://web.secom.to.gov.br">departamento</a> é responsável por manter a identidade visual dos sites do <a href="http://to.gov.br">Governo do Estado</a> e ainda fazemos os sites dos orgãos que não possuem um.</p>
<p>No trabalho sempre tivemos um constante problema para hospedar nossos sites: hardware!. Contamos hoje com dois incríveis servidores IBM Pentium4 3Ghz com 2gb de memória e HDs scsi, um para hospedar mais de 40 sites e o outro onde fica postgres com os bancos de dados desses sites.</p>
<p>Ultimamente nosso problema tem crescido bastante, pois, a demanda por sites aumentou e ao mesmo tempo o número de visitas veio aumentando e, como não conseguimos de forma alguma (até agora) investimento em equipamento novo estavamos chegando em uma situação crítica, nosso servidor começava a <del datetime="2009-10-15T12:28:06+00:00">sentar</del> morrer com 200 conexões simultaneas!</p>
<p>Lembrei-me de um <a href="http://www.boo-box.com/blog/br/2009/a-infraestrutura-de-servidores-web-do-sistema-boo-box/">post do boo-box</a> onde vi um servidor web chamado <a href="http://nginx.net">nginx</a> (lê-se engineX) e decidi pesquisar mais e fazer testes em casa onde rodando um servidor e servindo uma página php com um usleep de meio segundo consegui mais de 2000 conexões simultaneas! uau!..</p>
<p style="text-align: center;"><img class="aligncenter" title="nginx_performance" src="../wp-content/uploads/2009/10/nginx_performance.jpg" alt="nginx_performance" width="500" height="331" /></p>
<p>Na segunda feira seguinte, sem pensar muito, fui para o nosso servidor de produção e apliquei a seguinte política de funcionamento:</p>
<ul>
<li>nginx recebe todas as conexões pela porta 80</li>
<li>nginx faz proxy para o apache (que roda em outra porta) se a solicitação for para uma página php</li>
<li>nginx resolve sozinho usando php-cgi caso a requisição seja para:
<ul>
<li>uma fotografia</li>
<li>um arquivo</li>
<li>uma requisição para o webservice</li>
<li>um download do diário oficial</li>
<li>um banner do Governo</li>
<li>a barra padrão do Estado</li>
<li>ou um arquivo na nossa lib</li>
</ul>
</li>
</ul>
<p><del datetime="2009-11-15T10:54:02+00:00">Como resultado da experiência, nossos sites continuam morrendo, porém, aguentando 700 conexões simultaneas e esse valor só é alcançado quando tem muita pesquisa no banco de dados (Dias que sai algo sobre algum concurso público ou muita demissão no Diário Oficial) logo, fica claro, que o problema não é mais do webserver e sim do nosso servidor de Banco. Bom, o nosso webserver atualmente mal chega a 5% de uso, mesmo com as 700 conexões. Só espero conseguir uma maquina nova e mais eficiente para os nossos Bancos de Dados logo!.</del></p>
<p>Update:<br />
Fomos atendidos, estamos com um Xeon Quad Core com 4Gb de memória para o Banco de dados, e, associado com uma otimização do cache do webservice alcançamos mais de 1000 conexões simultâneas sem nenhuma degradação na performance. Detalhe que o webserver ainda é um P4 3ghz com 1gb de memória em que a utilização de processamento não passa de 5%.</p>
]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/nginx-webserver-proxy-reverso-e-perfeito/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Vórtice PHP Framework &#8211; Introdução</title>
		<link>http://ferrari.eti.br/vortice-php-framework-introducao/</link>
		<comments>http://ferrari.eti.br/vortice-php-framework-introducao/#comments</comments>
		<pubDate>Mon, 21 Sep 2009 10:55:38 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[vortice]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=63</guid>
		<description><![CDATA[Assim como frameworks mais conhecidos, o Vórtice tem uma estrutura de pastas que visa organizar todo o sistema e facilitar na hora da reutilização de código. segue abaixo a estrutura:
1 - app
1.1 - classes
1.2 - controller
1.2 - model
1.3 - view
1.4 - error_docs
1.5 - i18n
1.6 - plugins
2 - core
3 - css
4 - js
5 - templates
5.1 - [...]]]></description>
			<content:encoded><![CDATA[<p>Assim como frameworks mais conhecidos, o <a href="http://vortice.googlecode.com">Vórtice</a> tem uma estrutura de pastas que visa organizar todo o sistema e facilitar na hora da reutilização de código. segue abaixo a estrutura:</p>
<pre>1 - app
1.1 - classes
1.2 - controller
1.2 - model
1.3 - view
1.4 - error_docs
1.5 - i18n
1.6 - plugins
2 - core
3 - css
4 - js
5 - templates
5.1 - nome_do_seu_template
5.1.1 - css
5.1.2 - js</pre>
<h3>1 &#8211; App</h3>
<p>Apesar do framework não exigir nenhuma configuração em ambientes Linux/Unix ele possui um arquivo config.php que é necessário ser usado em caso de instalação em um ambiente Windows para definir a pasta fisica e a pasta virtual do sistema. ainda na pasta app existem os arquivos app.php e funcoes.php, que podem ser utilizados para inicializar instâncias de bancos de dados, criar funções e fazer qualquer coisa que você venha a precisar globalmente no seu site. Aqui também existe o arquivo route.php onde você poderá criar rotas baseadas em expressões regulares, tem um exemplo comentado de como funciona no sistema de exemplo.</p>
<h3>1.1 &#8211; classes</h3>
<p>Essa é a pasta de helpers, coloque ai suas classes de Segurança, as que modificam o fluxo do framework e qualquer classe que você venha a precisar no seu sistema</p>
<h3>1.2 &#8211; controller</h3>
<p>Pasta onde ficam os controllers, o nome do arquivo deve ser: CarroController.php, contendo dentro uma classe CarroController extendondo a classe Controller do framework. cada metodo dessa classe será uma action.</p>
<h3>1.2 &#8211; model</h3>
<p>Modelos do sistema, cada model é constituido por dois arquivos: Carro.php e CarroDAO.php contendo cada um a respectiva classe dentro. A classe Carro guarda a classe de um unico objeto carro (pode extender a classe de framework DTO) e a classe CarroDAO (quepode extender a classe de framework DAO) contêm as operações relacionadas ao objeto Carro (insert, delete, list, etc)</p>
<h3>1.3 &#8211; view</h3>
<p>Views do sistemas, uma view é um arquivo .php que será colocado dentro do template após a execução (substituindo o comentario &lt;!&#8211;conteudo&#8211;&gt; dentro do framework). Cada view deve ser colocada em uma subpasta com o nome do controller que ela pertence: app/view/carro/listar.php e será carregada automaticamente após a action listar do controller carro.</p>
<h3>1.4 &#8211; error_docs</h3>
<p>Páginas de erro, no framework já vem dois modelos.</p>
<h3>1.5 &#8211; i18n</h3>
<p>Pasta onde ficam traduções do sistema (en.conf, pt.conf, jp.conf, etc). Futuramente eu escrevo um post só sobre isso.</p>
<h3>1.6 &#8211; plugins</h3>
<p>Nessa pasta ficam plugins, que são executados exclusivamente antes da página ser enviada ao navegador. Futuramente eu escrevo sobre ela também.</p>
<h3>2 &#8211; core</h3>
<p>Aqui fica o nucleo do framework, caso você tenha vários sistemas usando ele, é possível criar um link simbólico e usar apenas uma pasta para todos os sites.</p>
<h3>3 &#8211; css</h3>
<p>Arquivos CSS globais, que serão carregados para todos os templates</p>
<h3>4 &#8211; js</h3>
<p>Arquivos JS globais, assim como a pasta css</p>
<h3>5 &#8211; templates</h3>
<p>Templates do site, cada subpasta será um template e dentro será necessário um arquivo template.php com o html básico da página.</p>
<h3>5.1.1 &#8211; css</h3>
<p>Aqui ficam os arquivos CSS exclusivos desse template</p>
<h3>5.1.2 &#8211; js</h3>
<p>Arquivos JS exclusivos do template</p>
<p>Fica ai toda a estrutura, qualquer dúvida deixe um comentário.</p>
<p>Faça já o download e experimente: <a href="http://vortice.googlecode.com">Projeto Vórtice PHP</a><br />
Siga o vórtice no twitter: <a href="http://twitter.com/vorticephp">@vorticephp</a> e acompanhe mais novidades seguindo <a href="http://twitter.com/caferrari">@caferrari</a> e <a href="http://twitter.com/luanlmd">@luanlmd</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/vortice-php-framework-introducao/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Vórtice PHP Framework &#8211; Apresentação</title>
		<link>http://ferrari.eti.br/vortice-php-framework-apresentacao/</link>
		<comments>http://ferrari.eti.br/vortice-php-framework-apresentacao/#comments</comments>
		<pubDate>Sat, 19 Sep 2009 10:42:47 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[vortice]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=51</guid>
		<description><![CDATA[Desde junho de 2008 eu e meus colegas do trabalho estamos desenvolvendo uma solução para usar nos sites do Governo do Tocantins e nos sistemas, como a gente tem problemas com a estrutura disponível (hardware!) decidimos criar um framework, que, além de agilizar nossa produção fosse extremamente rápido, consumisse o minimo de recursos possível e [...]]]></description>
			<content:encoded><![CDATA[<p>Desde junho de 2008 eu e meus colegas do trabalho estamos desenvolvendo uma solução para usar nos sites do Governo do Tocantins e nos sistemas, como a gente tem problemas com a estrutura disponível (hardware!) decidimos criar um framework, que, além de agilizar nossa produção fosse extremamente rápido, consumisse o minimo de recursos possível e permitisse o reaproveitamento de código.</p>
<p>Com menos de 2 meses de desenvolvimento, nascia o <a href="http://github.com/caferrari/vorticephp">Vórtice</a> junto com um <a href="http://faleconosco.to.gov.br">projeto inicial</a> que nos direcionou inicialmente no desenvolvimento.</p>
<p>Dentre as diversas características do framework, as mais importantes são:</p>
<ul>
<li> Velocidade;</li>
<li> Padrão MVC com Front Controller;</li>
<li>Rewrite de URL&#8217;s com suporte a regex;</li>
<li> Internacionalização com url&#8217;s únicas por idioma (queriamos que o google indexasse todas as línguas, ex: <a href="http://jalapao.to.gov.br">Jalapão</a>);</li>
<li>Ferramentas para mensagens de erro eficientes, tanto com ajax quanto sem;</li>
<li>O mínimo de configuração possível (no linux não exige nenhuma configuração!);</li>
<li>Fosse possível se conectar em multiplos bancos de dados;</li>
<li>PDO!</li>
<li>Pronto para funcionar com Ajax;</li>
<li>Nos desse algo para trabalhar com versões mobile dos sites;</li>
<li>Renderização em HTML, Json, XML, phpserialize, etc..</li>
</ul>
<p>Veja as demais características no <a href="http://github.com/caferrari/vorticephp">site do projeto</a>.</p>
<p>O projeto quase não foi divulgado devido a falta de Documentação, porém, hoje, como ele está extremamente estável decidi criar este post para apresentá-lo. caso você queira testar, é só <a href="http://github.com/caferrari/vorticephp">baixar</a> e brincar. Ele já vem com um projeto de exemplo que ajuda a ter uma noção legal das funcionalidades.</p>
<p>Para finalizar alguns projetos usando ele:</p>
<ul>
<li><a href="http://to.gov.br">http://to.gov.br</a></li>
<li><a href="http://jalapao.to.gov.br">http://jalapao.to.gov.br</a></li>
<li><a href="http://secom.to.gov.br">http://secom.to.gov.br</a></li>
</ul>
<p>Aguardo comentários.</p>
]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/vortice-php-framework-apresentacao/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Criando Tweets pelo PHP</title>
		<link>http://ferrari.eti.br/criando-tweets-pelo-php/</link>
		<comments>http://ferrari.eti.br/criando-tweets-pelo-php/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 15:32:03 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[classes]]></category>
		<category><![CDATA[tweet]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=33</guid>
		<description><![CDATA[Sou responsável por um site de notícias e hoje precisei criar um meio de que quando uma notícia for inserida no site, ser criado automaticamente um tweet no twitter lincando para ela, a solução foi essa classe abaixo:

class Tweet&#123;
	var $user;
	var $pass;
	var $json = false;
&#160;
	function __construct&#40;$user, $pass, $texto=false&#41;&#123;
		$this-&#38;gt;user = $user;
		$this-&#38;gt;pass = $pass;
		if &#40;$texto&#41; $this-&#38;gt;send&#40;$texto&#41;;
	&#125;
&#160;
	private function testTweet&#40;$texto, [...]]]></description>
			<content:encoded><![CDATA[<p>Sou responsável por um site de notícias e hoje precisei criar um meio de que quando uma notícia for inserida no site, ser criado automaticamente um tweet no <a href="http://twitter.com">twitter</a> lincando para ela, a solução foi essa classe abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Tweet<span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$pass</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$json</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #339933;">,</span> <span style="color: #000088;">$pass</span><span style="color: #339933;">,</span> <span style="color: #000088;">$texto</span><span style="color: #339933;">=</span><span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>user <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>pass <span style="color: #339933;">=</span> <span style="color: #000088;">$pass</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #009900;">&#41;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>send<span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">function</span> testTweet<span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">,</span> <span style="color: #000088;">$match</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$match</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$m</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$url</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$m</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: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">ereg</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;^www&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000088;">$url</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://<span style="color: #006699; font-weight: bold;">$url</span>&quot;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">19</span><span style="color: #009900;">&#41;</span> <span style="color: #000088;">$url</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_repeat</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;x&quot;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">19</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$texto</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$m</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;">$url</span><span style="color: #339933;">,</span> <span style="color: #000088;">$texto</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #000088;">$texto</span> <span style="color: #339933;">=</span> <span style="color: #990000;">ereg_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;http://(x{19,})&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\\</span>1&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$texto</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">140</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
		<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>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> makeUrl<span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</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;">ereg</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;^www&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000088;">$url</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://<span style="color: #006699; font-weight: bold;">$url</span>&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;=</span> <span style="color: #cc66cc;">19</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> <span style="color: #000088;">$url</span><span style="color: #339933;">;</span>
		<span style="color: #000088;">$url</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://migre.me/atalho/&quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">urlencode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #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>
		<span style="color: #990000;">curl_setopt_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
			CURLOPT_URL <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$url</span><span style="color: #339933;">,</span>
			CURLOPT_RETURNTRANSFER <span style="color: #339933;">=&amp;</span>gt<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: #339933;">;</span>
		<span style="color: #000088;">$o</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>
		<span style="color: #990000;">ereg</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;value=<span style="color: #000099; font-weight: bold;">\&quot;</span>(http://migre.me/[a-zA-Z0-9/:]+)<span style="color: #000099; font-weight: bold;">\&quot;</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$o</span><span style="color: #339933;">,</span> <span style="color: #000088;">$mat</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$mat</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;">&#125;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> send<span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</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;">function_exists</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;curl_init&quot;</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;">// Localiza as URLs</span>
			<span style="color: #990000;">preg_match_all</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/((https?:\/\/)|(www))([a-zA-Z0-9\/:%&amp;amp;\?\.=\-\+]+)/&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$texto</span><span style="color: #339933;">,</span> <span style="color: #000088;">$match</span><span style="color: #339933;">,</span> PREG_SET_ORDER <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #666666; font-style: italic;">// Testa se o tamanho do twitter é aceitavel</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>testTweet<span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #339933;">,</span> <span style="color: #000088;">$match</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> throw <span style="color: #000000; font-weight: bold;">new</span> Exception <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Postagem muito longa!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #666666; font-style: italic;">// Cria as URLs finais</span>
			<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$match</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$m</span><span style="color: #009900;">&#41;</span> <span style="color: #000088;">$texto</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$m</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;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>makeUrl<span style="color: #009900;">&#40;</span><span style="color: #000088;">$m</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$texto</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$texto</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;http://http://&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;http://&quot;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$texto</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #666666; font-style: italic;">// Testa novamente pelo comprimento do tweet</span>
			<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$texto</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">140</span><span style="color: #009900;">&#41;</span> throw <span style="color: #000000; font-weight: bold;">new</span> Exception <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Postagem muito longa!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #666666; font-style: italic;">// Envia o tweet</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>
			<span style="color: #990000;">curl_setopt_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$ch</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
				CURLOPT_URL <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">&quot;http://twitter.com/statuses/update.json&quot;</span><span style="color: #339933;">,</span>
				CURLOPT_HTTPHEADER <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Expect:'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
				CURLOPT_POST <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span>
				CURLOPT_POSTFIELDS <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;status&quot;</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">&quot;<span style="color: #006699; font-weight: bold;">{$texto}</span>&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
				CURLOPT_HTTPAUTH <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> CURLAUTH_ANY<span style="color: #339933;">,</span>
				CURLOPT_RETURNTRANSFER <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">,</span>
				CURLOPT_USERPWD <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">&quot;{<span style="color: #006699; font-weight: bold;">$this</span>-&amp;gt;user}:{<span style="color: #006699; font-weight: bold;">$this</span>-&amp;gt;pass}&quot;</span><span style="color: #009900;">&#41;</span>
			<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>json <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>
		<span style="color: #009900;">&#125;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>json <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>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000088;">$tmp</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Tweet<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;username&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;password&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$tmp</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>send<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Eu não gosto das URLs do site da Microsoft: http://search.microsoft.com/results.aspx?form=MSHOME&amp;amp;setlang=en-us&amp;amp;q=office+templates&amp;amp;mkt=en-US&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Ela faz a análise do seu texto e converte as URLs, caso necessário, para um formato resumido usando o <a href="http://migre.me">migre.me</a> e caso passe os 140 caracteres uma exception é jogada.</p>
]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/criando-tweets-pelo-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Links encriptados no PHP</title>
		<link>http://ferrari.eti.br/links-encriptados-no-php/</link>
		<comments>http://ferrari.eti.br/links-encriptados-no-php/#comments</comments>
		<pubDate>Wed, 11 Jun 2008 13:27:07 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[criptografia]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=11</guid>
		<description><![CDATA[Nesse post vou exemplificar como utilizar a classe XOR exemplificada no post Operador XOR no PHP para criação de URLs encriptadas usando uma espécie de checksum que irá impedir que alguem possa alrera-la. as vantagens dessa técnica são:

URLs camufladas
PHP camuflado
Variáveis passadas pela URL sempre válidas
Impossibilidade de Modificação da querystring manualmente

Aqui está o exemplo de hoje: [...]]]></description>
			<content:encoded><![CDATA[<p>Nesse post vou exemplificar como utilizar a classe <a href="http://pt.wikipedia.org/wiki/XOR">XOR</a> exemplificada no post <a href="http://ferrari.eti.br/operador-xor-no-php/">Operador XOR no PHP</a> para criação de URLs encriptadas usando uma espécie de <a href="http://pt.wikipedia.org/wiki/Checksum">checksum</a> que irá impedir que alguem possa alrera-la. as vantagens dessa técnica são:</p>
<ul>
<li>URLs camufladas</li>
<li>PHP camuflado</li>
<li>Variáveis passadas pela URL sempre válidas</li>
<li>Impossibilidade de Modificação da querystring manualmente</li>
</ul>
<p>Aqui está o exemplo de hoje: <a href="http://ferrari.eti.br/exemplos/fw1" target="_blank">http://ferrari.eti.br/exemplos/fw1</a></p>
<p>Esse exemplo utiliza <a href="http://json.org/json-pt.html">jSon</a>, se você não sabe o que é, veja <a href="http://json.org/json-pt.html">aqui</a>.</p>
<p>Para começar, vamos criar o arquivo: includes/classes/crypt.php e colocar o código do post: <a href="http://ferrari.eti.br/operador-xor-no-php/">Operador XOR no PHP</a>.</p>
<p>Depois criaremos a nossa classe mais importante: includes/classes/link.php e vamos edita-lá:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// incluímos a classe de criptografia</span>
<span style="color: #b1b100;">require_once</span> <span style="color: #0000ff;">&quot;crypt.php&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Variavel global similar a $_POST, porém sua função é</span>
<span style="color: #666666; font-style: italic;">// armazenar os valores passados pela querystring</span>
<span style="color: #000088;">$_PAR</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</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;">class</span> <span style="color: #990000;">Link</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// Variável que armazena a chave do checksum</span>
     static <span style="color: #000088;">$chave</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;chavedockecksum&quot;</span><span style="color: #339933;">;</span>
&nbsp;
     <span style="color: #666666; font-style: italic;">// Variável que armazena o link</span>
     <span style="color: #000000; font-weight: bold;">var</span> <span style="color: #000088;">$link</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">;</span>
&nbsp;
     <span style="color: #666666; font-style: italic;">// construtor, os parâmetros são simples</span>
     <span style="color: #666666; font-style: italic;">// pagina = arquovo php a ser chamado</span>
     <span style="color: #666666; font-style: italic;">// parametros: parâmetros da chamada ex: &quot;id=10&amp;amp;tipo=noticia&quot;</span>
     <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #990000;">Link</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$pagina</span><span style="color: #339933;">=</span><span style="color: #0000ff;">''</span><span style="color: #339933;">,</span> <span style="color: #000088;">$parametros</span><span style="color: #339933;">=</span><span style="color: #0000ff;">''</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          <span style="color: #666666; font-style: italic;">// chama o método responsável pela criação do link</span>
          <span style="color: #666666; font-style: italic;">// repassando os parâmetros</span>
          <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>link <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>criaLink<span style="color: #009900;">&#40;</span><span style="color: #000088;">$pagina</span><span style="color: #339933;">,</span> <span style="color: #000088;">$parametros</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
          <span style="color: #666666; font-style: italic;">// retorna o link encriptado</span>
          <span style="color: #b1b100;">return</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>link<span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
     static <span style="color: #000000; font-weight: bold;">function</span> criaLink<span style="color: #009900;">&#40;</span><span style="color: #000088;">$pagina</span><span style="color: #339933;">=</span><span style="color: #0000ff;">''</span><span style="color: #339933;">,</span> <span style="color: #000088;">$parametros</span><span style="color: #339933;">=</span><span style="color: #0000ff;">''</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          <span style="color: #666666; font-style: italic;">// transforma os parâmetros em um array associativo</span>
          <span style="color: #990000;">parse_str</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$parametros</span><span style="color: #339933;">,</span> <span style="color: #000088;">$p</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
          <span style="color: #666666; font-style: italic;">// adiciono nesse array na posição &quot;_pagina&quot; o arquivo php</span>
          <span style="color: #000088;">$p</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;_pagina&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$pagina</span><span style="color: #339933;">;</span>
&nbsp;
          <span style="color: #666666; font-style: italic;">// Aqui eu adiciono uma chave calculada a partir do que tem no array $p</span>
          <span style="color: #666666; font-style: italic;">// porém adiciono somente os 5 primeiros caracteres para encurtar a chave</span>
          <span style="color: #666666; font-style: italic;">// esse será o parâmetro responsável por garantir a integridade</span>
          <span style="color: #666666; font-style: italic;">// da informação passada</span>
          <span style="color: #000088;">$p</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;_check&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">crypt</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">json_encode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$p</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">Link</span><span style="color: #339933;">::</span><span style="color: #000088;">$chave</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
         <span style="color: #666666; font-style: italic;">// retornamos a URL encriptando a versão codificada em json dela.</span>
         <span style="color: #666666; font-style: italic;">// rootvirtual é a constante que diz qual o root do site,</span>
         <span style="color: #666666; font-style: italic;">// explicarei mais abaixo de onde ela vem</span>
         <span style="color: #b1b100;">return</span> rootvirtual <span style="color: #339933;">.</span> <span style="color: #0000ff;">&quot;?&quot;</span> <span style="color: #339933;">.</span> <span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #004000;">Encrypt</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">json_encode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$p</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
     static <span style="color: #000000; font-weight: bold;">function</span> trataQuery<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          <span style="color: #666666; font-style: italic;">// verifica a existência de query-string e adiciona ela na variável $q</span>
          <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$q</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'QUERY_STRING'</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;">// decodifica a string</span>
               <span style="color: #000088;">$p</span> <span style="color: #339933;">=</span> <span style="color: #990000;">json_decode</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #004000;">Decrypt</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$q</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: #339933;">;</span>
                    <span style="color: #666666; font-style: italic;">// se o retorno for um array, quer dizer que a query é parcialmente válida</span>
                    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">is_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$p</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> <span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$p</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;_check&quot;</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: #666666; font-style: italic;">// carrega a chave do vetor</span>
                        <span style="color: #000088;">$chave</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$p</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;_check&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
                        <span style="color: #666666; font-style: italic;">// remove a chave do vetor</span>
                        <span style="color: #990000;">unset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$p</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;_check&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        <span style="color: #666666; font-style: italic;">// recalcula a chave e verifica se é diferente a chave passada</span>
                        <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">crypt</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">json_encode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$p</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">Link</span><span style="color: #339933;">::</span><span style="color: #000088;">$chave</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</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: #000088;">$chave</span><span style="color: #009900;">&#41;</span>
                             <span style="color: #666666; font-style: italic;">// Se for, a requisição eh redirecionada para o index.</span>
                             <span style="color: #990000;">header</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Location: &quot;</span> <span style="color: #339933;">.</span> rootvirtual<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                        <span style="color: #b1b100;">else</span><span style="color: #009900;">&#123;</span>
                             <span style="color: #666666; font-style: italic;">// se for válida é criada a variável global _PAR e o vetor</span>
                             <span style="color: #666666; font-style: italic;">// de parâmetros é jogado nela</span>
                             <span style="color: #000088;">$GLOBALS</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;_PAR&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$p</span><span style="color: #339933;">;</span>
                             <span style="color: #666666; font-style: italic;">// sai da função</span>
                             <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: #009900;">&#125;</span><span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
                     <span style="color: #666666; font-style: italic;">// se não for um vetor, houve modificação da url, e a requisição</span>
                     <span style="color: #666666; font-style: italic;">// é enviada para o index</span>
                     <span style="color: #990000;">header</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Location: &quot;</span> <span style="color: #339933;">.</span> rootvirtual<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
               <span style="color: #009900;">&#125;</span>
               <span style="color: #666666; font-style: italic;">// termina a execução e redireciona</span>
               <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</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: #009900;">&#125;</span></pre></div></div>

<p>Agora vamos para a criação de três arquivos base do site e partir para um exemplo funcional.</p>
<p>o arquivo: includes/config.php irá armazenar as configurações básicas do site:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Root no servidor do site</span>
<span style="color: #990000;">define</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;rootfisico&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;/var/www/fw/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Pasta do site no servidor</span>
<span style="color: #990000;">define</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;rootvirtual&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;/fw/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// As linhas abaixo são a parte interessante do sistema, pra que usar chaves</span>
<span style="color: #666666; font-style: italic;">// fixas se podemos definidas randomicamente a cada acesso ao sistema?</span>
<span style="color: #666666; font-style: italic;">// assim, uma url usada por uma pessoa só será valida pra ela naquele acesso</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;cryptKey&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;cryptKey&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">crypt</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">uniqid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;cryptKey2&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;cryptKey2&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #990000;">crypt</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">uniqid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #000088;">$chave</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;cryptKey&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">Link</span><span style="color: #339933;">::</span><span style="color: #000088;">$chave</span> <span style="color: #339933;">=</span>  <span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;cryptKey2&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Arquivo: includes/funcoes.php</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Essa função irá retornar valores de $_POST['var'] ou $_PAR['$var']</span>
<span style="color: #000000; font-weight: bold;">function</span> p<span style="color: #009900;">&#40;</span><span style="color: #000088;">$v</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$_POST</span><span style="color: #339933;">,</span> <span style="color: #000088;">$_PAR</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$v</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> ? <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$v</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_PAR</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$v</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> ? <span style="color: #000088;">$_PAR</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$v</span><span style="color: #009900;">&#93;</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: #009900;">&#125;</span></pre></div></div>

<p>Arquivo: includes/inicio.php</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Definimos o charset e inicializamos a session</span>
<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>
<span style="color: #339933;">@</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: #666666; font-style: italic;">// incluímos as classes e os outros arquivos</span>
<span style="color: #b1b100;">include</span> <span style="color: #0000ff;">&quot;funcoes.php&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">include</span> <span style="color: #0000ff;">&quot;classes/link.php&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">include</span> <span style="color: #0000ff;">&quot;config.php&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// agora tratamos a URL atual</span>
<span style="color: #990000;">Link</span><span style="color: #339933;">::</span><span style="color: #004000;">trataQuery</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Ufs. finalmente chegou a hora, vamos botar o sistema de Links para funcionar e vamos brincar com ele um pouco. vamos criar o arquivo /index.php</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">Exemplo de <span style="color: #990000;">Link</span><span style="color: #339933;">:</span>
&nbsp;
<span style="color: #339933;">&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&amp;lt;? echo Link::criaLink('') ?&amp;gt;&quot;</span><span style="color: #339933;">&gt;</span>Página inicial<span style="color: #339933;">&lt;/</span>a<span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #339933;">&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&amp;lt;? echo Link::criaLink('usuarios.php', 'id=10') ?&amp;gt;&quot;</span><span style="color: #339933;">&gt;</span>Exemplo <span style="color: #cc66cc;">1</span><span style="color: #339933;">&lt;/</span>a<span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #339933;">&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&amp;lt;? echo Link::criaLink('principal.php') ?&amp;gt;&quot;</span><span style="color: #339933;">&gt;</span>Exemplo <span style="color: #cc66cc;">2</span><span style="color: #339933;">&lt;/</span>a<span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #339933;">&lt;</span>a href<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&amp;lt;? echo Link::criaLink('noticia.php', 'id=10&amp;amp;tipo=ultima&amp;amp;skin=azul') ?&amp;gt;&quot;</span><span style="color: #339933;">&gt;</span>Exemplo <span style="color: #cc66cc;">3</span><span style="color: #339933;">&lt;/</span>a<span style="color: #339933;">&gt;</span>
&nbsp;
Parabéns<span style="color: #339933;">,</span> a página  foi passada
<span style="color: #339933;">&lt;</span>h2<span style="color: #339933;">&gt;</span>Página Inicial<span style="color: #339933;">&lt;/</span>h2<span style="color: #339933;">&gt;</span>
Nenhuma página passada<span style="color: #339933;">,</span> ou alguem tentou mudar a URL
&nbsp;
Resultados<span style="color: #339933;">:</span>
&nbsp;
<span style="color: #339933;">&lt;</span>strong<span style="color: #339933;">&gt;</span>Página<span style="color: #339933;">:&lt;/</span>strong<span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #339933;">&lt;</span>strong<span style="color: #339933;">&gt;</span>Parametros<span style="color: #339933;">:&lt;/</span>strong<span style="color: #339933;">&gt;</span></pre></div></div>

<p>Bom, é isso. espero que tenha sido bem explicado um exemplo funcional e arquivo para download está aqui: <a href="http://ferrari.eti.br/exemplos/fw1" target="_blank">http://ferrari.eti.br/exemplos/fw1</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/links-encriptados-no-php/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Operador XOR no PHP</title>
		<link>http://ferrari.eti.br/operador-xor-no-php/</link>
		<comments>http://ferrari.eti.br/operador-xor-no-php/#comments</comments>
		<pubDate>Wed, 21 May 2008 19:00:59 +0000</pubDate>
		<dc:creator>caferrari</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[classes]]></category>
		<category><![CDATA[criptografia]]></category>

		<guid isPermaLink="false">http://ferrari.eti.br/?p=6</guid>
		<description><![CDATA[Há alguns meses estava precisando criar uma classe de criptografia e quando eu fui desenvolver eu não encontrei nenhuma criptografia veloz o suficiente, até que o Luan me mostrou uma excelente utilização para o XOR. Este operador é muito parecido com o OR, porém a sua leitura é: &#8220;OU um OU outro&#8221; e não &#8220;UM [...]]]></description>
			<content:encoded><![CDATA[<p>Há alguns meses estava precisando criar uma classe de criptografia e quando eu fui desenvolver eu não encontrei nenhuma criptografia veloz o suficiente, até que o <a href="http://luan.eti.br">Luan</a> me mostrou uma excelente utilização para o <a href="http://en.wikipedia.org/wiki/Exclusive_or">XOR</a>. Este operador é muito parecido com o <a href="http://en.wikipedia.org/wiki/Or">OR</a>, porém a sua leitura é: &#8220;OU um OU outro&#8221; e não &#8220;UM ou OUTRO&#8221; como o <a href="http://en.wikipedia.org/wiki/Or">OR</a>. Confira a tabela abaixo exemplificando:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009900; font-weight: bold;">false</span> ^ <span style="color: #009900; font-weight: bold;">false</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span>
<span style="color: #009900; font-weight: bold;">false</span> ^ <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">true</span>
<span style="color: #009900; font-weight: bold;">true</span> ^ <span style="color: #009900; font-weight: bold;">true</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span>
<span style="color: #009900; font-weight: bold;">true</span> ^ <span style="color: #009900; font-weight: bold;">false</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">true</span></pre></div></div>

<p>Legal não? só é verdadeiro se os valores forem diferentes.</p>
<p>Como exemplo vamos pegar 2 valores binários, como sendo uma chave e um valor:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">valor<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;11010110&quot;</span>
chave<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;10011101&quot;</span></pre></div></div>

<p>Vamos operar cada bit usando o <a href="http://en.wikipedia.org/wiki/Exclusive_or">XOR</a>, isso irá resultar o binário &#8220;encriptado&#8221;</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #cc66cc;">11010110</span> ^ <span style="color: #009900;">&#40;</span>valor<span style="color: #009900;">&#41;</span>
<span style="color: #cc66cc;">10011101</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>chave<span style="color: #009900;">&#41;</span>
<span style="color: #208080;">01001011</span>    <span style="color: #009900;">&#40;</span>valor encriptado<span style="color: #009900;">&#41;</span></pre></div></div>

<p>Na terceira linha obtivemos o valor encriptado, só para demonstrar, vamos usar esse valor encriptado e dar um <a href="http://en.wikipedia.org/wiki/Exclusive_or">XOR</a> com a chave novamente.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #208080;">01001011</span> ^ <span style="color: #009900;">&#40;</span>valor encriptado<span style="color: #009900;">&#41;</span>
<span style="color: #cc66cc;">10011101</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>chave<span style="color: #009900;">&#41;</span>
<span style="color: #cc66cc;">11010110</span>   <span style="color: #009900;">&#40;</span>valor novamente<span style="color: #009900;">&#41;</span></pre></div></div>

<p>Não precisa de mais exemplos certo? é uma forma fraca, porém muito veloz de gerar criptografia, e perfeita para usarmos em coisas simples, como a criptografia de URL&#8217;s e <a href="http://en.wikipedia.org/wiki/Salt_%28cryptography%29">Salts</a></p>
<p>Mas não pense que programar isso é complexo, o <a href="http://br.php.net">PHP</a> permite que façamos esse processo usando dois caracteres.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #0000ff;">&quot;a&quot;</span> ^ <span style="color: #0000ff;">&quot;b&quot;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;?&quot;</span><span style="color: #339933;">,</span> logo
<span style="color: #0000ff;">&quot;?&quot;</span> ^ <span style="color: #0000ff;">&quot;b&quot;</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;a&quot;</span></pre></div></div>

<p>Com isso vou mostrar uma classe de criptografia extremamente simples:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> <span style="color: #990000;">Crypt</span> <span style="color: #009900;">&#123;</span>
    static <span style="color: #000088;">$chave</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;xy&quot;</span><span style="color: #339933;">;</span>
    static <span style="color: #000000; font-weight: bold;">function</span> StringXor<span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #339933;">,</span><span style="color: #000088;">$b</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;">$a</span><span style="color: #339933;">==</span><span style="color: #0000ff;">''</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$retorno</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span> <span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span> <span style="color: #000088;">$j</span> <span style="color: #339933;">=</span> <span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$b</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">do</span><span style="color: #009900;">&#123;</span>
            <span style="color: #000088;">$retorno</span> <span style="color: #339933;">.=</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #009900;">&#123;</span><span style="color: #000088;">$i</span><span style="color: #009900;">&#125;</span> ^ <span style="color: #000088;">$b</span><span style="color: #009900;">&#123;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">%</span> <span style="color: #000088;">$j</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span><span style="color: #339933;">--</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #990000;">strrev</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$retorno</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    static <span style="color: #000000; font-weight: bold;">function</span> Encrypt<span style="color: #009900;">&#40;</span><span style="color: #000088;">$string</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #990000;">base64_encode</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #004000;">StringXor</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$string</span><span style="color: #339933;">,</span> <span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #000088;">$chave</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    static <span style="color: #000000; font-weight: bold;">function</span> Decrypt<span style="color: #009900;">&#40;</span><span style="color: #000088;">$string</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #004000;">StringXor</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">base64_decode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #000088;">$chave</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>O que essa classe faz basicamente é percorrer as strings da chave e do valor passado, calculando para cada caractere o seu valor encriptado, e ao final é codificado usando-se base64 para que não fique com caracteres inválidos na string.</p>
<p>Um exemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">texto <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;andre&quot;</span>
chave <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;xy&quot;</span>
resultado<span style="color: #339933;">:</span>
a ^ x
n ^ y
d ^ x
r ^ y
e ^ x</pre></div></div>

<p>Código php:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #004000;">Encrypt</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;andre&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Encriptado:&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$b</span> <span style="color: #339933;">=</span> <span style="color: #990000;">Crypt</span><span style="color: #339933;">::</span><span style="color: #004000;">Decrypt</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$a</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Decriptado: <span style="color: #006699; font-weight: bold;">$b</span>&quot;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Saída:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">Encriptado<span style="color: #339933;">:</span> GRccCx0<span style="color: #339933;">=</span>
Decriptado<span style="color: #339933;">:</span> andre</pre></div></div>

<p>é isso, testem, entendam e qualquer coisa pergunte.</p>
]]></content:encoded>
			<wfw:commentRss>http://ferrari.eti.br/operador-xor-no-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
