<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-3692489238488225957</id><updated>2024-12-19T00:22:58.725-03:00</updated><category term="JavaScript"/><category term="PHP"/><category term="MySQL"/><category term="PostgreSQL"/><title type='text'>Extremo Conhecimento - Compartilhando Dicas e Tutoriais</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>9</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-5730049476418358265</id><published>2015-06-10T15:12:00.001-03:00</published><updated>2015-06-10T15:45:44.296-03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="PostgreSQL"/><title type='text'>Formatar números decimais com PostgreSQL</title><content type='html'>Nesta postagem quero compartilhar com vocês uma função para formatar números decimais em PostgreSQL.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: sql&quot;&gt;create or replace function format_number (_number numeric, decimals integer, decimal_symbol char, thousands_symbol char)
  returns varchar as
$BODY$
declare
    _value varchar;
    _index integer;
    _values varchar[2];
    i integer;
    pos integer;
begin
    _value = round(_number, decimals)::varchar;
    _index = strpos(_value, &#39;.&#39;);

    _values[0] = _value;
    _values[1] = &#39;&#39;;
    if (_index &amp;gt; 0) then
        _values[0] = substr(_value, 0, _index);
        _values[1] = decimal_symbol || substr(_value, _index+1);        
    end if;
    
    i = 0;
    while (i &amp;lt; floor((length(_values[0]) - (i+1)) / 3)) loop
        pos = length(_values[0]) - (4 * i+2);
        _values[0] = substr(_values[0], 0, pos) || thousands_symbol || substr(_values[0], pos);    
        i = i+1;
    end loop;
    
    return _values[0] || _values[1];
end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100; 
&lt;/pre&gt;
&lt;br /&gt;
Exemplo de uso:&lt;br /&gt;
&lt;br /&gt;
SELECT format_number(minha_coluna) FROM minha_tabela</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/5730049476418358265/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/5730049476418358265' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/5730049476418358265'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/5730049476418358265'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2015/06/formatar-numeros-decimais-com-postgresql.html' title='Formatar números decimais com PostgreSQL'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-6427342630996089935</id><published>2013-02-18T21:09:00.001-03:00</published><updated>2013-02-18T21:24:09.121-03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="MySQL"/><title type='text'>Implementando Algoritmo BuscaBR em MySQL</title><content type='html'>A necessidade de melhoria no acesso aos dados armazenados em grandes Banco de Dados&lt;br /&gt;
tem levado as empresas a buscarem formas práticas de tornar as consultas mais eficientes. &lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgh_nrAM4Q9m7i0EDwPsUJbo1-LnX-tow6L5vtbd1a8jZWmuGS3nxs1FZmq46OA-u39iSLOHtdtbJbEt-a_t6cwFxCQAIUxpwwOhBXOxLDBwU7oNnnYVDoFHsk9o2DtkEt89rRvMiCY-yc/s1600/MySQL.jpg&quot; imageanchor=&quot;1&quot; style=&quot;clear: left; float: left; margin-bottom: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgh_nrAM4Q9m7i0EDwPsUJbo1-LnX-tow6L5vtbd1a8jZWmuGS3nxs1FZmq46OA-u39iSLOHtdtbJbEt-a_t6cwFxCQAIUxpwwOhBXOxLDBwU7oNnnYVDoFHsk9o2DtkEt89rRvMiCY-yc/s1600/MySQL.jpg&quot; /&gt;&lt;/a&gt;Como se já não bastasse às dificuldades que são geradas através da grafia da língua falada ou escrita quer pela ortografia e gramática oficial ou pelas influências externas à língua portuguesa utilizada no Brasil também possui as suas regras ortográficas e gramaticais além de uma grande quantidade de influências internas e externas que dificultam o seu aprendizado. Também o estrangeirismo é muito presente e termina por criar novas palavras que são incorporadas na sua grafia original ou sofrem aportuguesamento, gerando assim, novas dificuldades e às vezes criando exceções as regras existentes. &lt;br /&gt;
Isso deixa os bancos de dados cada vez mais desorganizadas e nem sempre temos o retorno esperado quando fazemos uma consulta.&lt;br /&gt;
&lt;br /&gt;
Devido a isso foi criado a rotina SoundEx (registrado por Robert Russell e Margaret Odell) nos Estados Unidos em 1918 para tentar minimizar as informações, a rotina codificava os fonemas para corrigir a grafia errada das palavras, mas a rotina supria as necessidades norte americanas, mas na realidade brasileira comprometeu a eficiência. Devido a isso foi criado uma função capaz de abordar todas as características da língua portuguesa, com base em um estudo das deficiências do SoundEx foi desenvolvido uma análise detalhada dos fonemas da língua portuguesa e também os erros de grafia que foram cometidos. Por fim, chegou-se a função PL/SQL (registrado pelo Oracle) com o nome de BuscaBR e que na língua portuguesa foi bastante eficaz.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;O que é o BuscaBR?&lt;/b&gt;&lt;br /&gt;
Nada mais é do que uma rotina para indexar sua base de dados.&lt;br /&gt;
&lt;br /&gt;
Eu implementei duas funções em MySQL, a principal é a &quot;phonembr&quot; e ela que será utilizada indexar as palavras, a outra função serve apenas para normalizar a string.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:sql&quot;&gt;drop function if exists phonembr_normalize;
delimiter //
create function phonembr_normalize(str varchar(255))
returns varchar(255)
begin
&amp;nbsp;&amp;nbsp;&amp;nbsp; declare pos int;
&amp;nbsp;&amp;nbsp;&amp;nbsp; declare chars_special varchar(255);
&amp;nbsp;&amp;nbsp;&amp;nbsp; declare chars_normal varchar(255);&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set chars_special = &#39;ÁÀÃÂÉÊÍÓÔÕÚÜ&#39;;
&amp;nbsp;&amp;nbsp;&amp;nbsp; set chars_normal = &#39;AAAAEEIOOOUU&#39;;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = upper(str);&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set pos = length(chars_normal);&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; while pos &amp;gt; 0 do
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, substring(chars_special, pos, 1), substring(chars_normal, pos, 1));
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set pos = pos-1;
&amp;nbsp;&amp;nbsp;&amp;nbsp; end while;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = trim(str);
&amp;nbsp;&amp;nbsp;&amp;nbsp; while str regexp &#39; {2,}&#39; do 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;&amp;nbsp; &#39;, &#39; &#39;);
&amp;nbsp;&amp;nbsp;&amp;nbsp; end while;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set pos = length(str);
&amp;nbsp;&amp;nbsp;&amp;nbsp; while pos &amp;gt; 0 do 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; if substring(str, pos, 1) regexp &#39;[^A-Z0-9Ç@._ +-]+&#39; then
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = concat(substring(str, 1, pos-1), substring(str, pos+1));
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; end if;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set pos = pos-1;
&amp;nbsp;&amp;nbsp;&amp;nbsp; end while;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; 

&amp;nbsp;&amp;nbsp;&amp;nbsp; return str;
end //
delimiter ;

drop function if exists phonembr;
delimiter //
create function phonembr(str varchar(255))
returns varchar(255)
begin
&amp;nbsp;&amp;nbsp;&amp;nbsp; declare pos int;
&amp;nbsp;&amp;nbsp;&amp;nbsp; declare break tinyint;
&amp;nbsp;&amp;nbsp;&amp;nbsp; declare chars_s varchar(255);
&amp;nbsp;&amp;nbsp;&amp;nbsp; declare chars_r varchar(255);
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = phonembr_normalize(str);&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set chars_s = &#39;BL,BR,CA,CE,CI,CO,CU,CK,Ç,CH,CS,CT,GE,GI,GM,GL,GR,L,N,MD,MG,MJ,PH,PR,Q,RG,RS,RT,RM,RJ,ST,TR,TL,TS,W,X,Y,Z&#39;;
&amp;nbsp;&amp;nbsp;&amp;nbsp; set chars_r = &#39;B,B,K,S,S,K,K,K,S,S,S,T,J,J,M,G,G,R,M,M,G,J,F,P,K,G,S,T,SM,J,T,T,T,S,V,S,I,S&#39;;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set break = 0;
&amp;nbsp;&amp;nbsp;&amp;nbsp; while not break do 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, substring_index(chars_s, &#39;,&#39;, 1), substring_index(chars_r, &#39;,&#39;, 1));&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; if not locate(&#39;,&#39;, chars_s) then
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set break = 1;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; else
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set chars_s = substring(chars_s, locate(&#39;,&#39;, chars_s)+1);
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set chars_r = substring(chars_r, locate(&#39;,&#39;, chars_r)+1);
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; end if;&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; end while;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; if str regexp &#39;[A-Z]+[MRS] &#39; then
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;M &#39;, &#39; &#39;);
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;R &#39;, &#39; &#39;);
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;S &#39;, &#39; &#39;);
&amp;nbsp;&amp;nbsp;&amp;nbsp; end if;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; if str regexp &#39;[A-Z]+[MRS]$&#39; then
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = substr(str, 1, length(str)-1);
&amp;nbsp;&amp;nbsp;&amp;nbsp; end if;
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;A&#39;, &#39;&#39;);
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;E&#39;, &#39;&#39;);
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;I&#39;, &#39;&#39;);&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;O&#39;, &#39;&#39;);
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;U&#39;, &#39;&#39;);
&amp;nbsp;&amp;nbsp;&amp;nbsp; set str = replace(str, &#39;H&#39;, &#39;&#39;);&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; 
&amp;nbsp;&amp;nbsp;&amp;nbsp; set pos = length(str);
&amp;nbsp;&amp;nbsp;&amp;nbsp; while pos &amp;gt; 0 do 
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; if substr(str, pos, 1) = substr(str, pos-1, 1) then
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set str = concat(substr(str, 1, pos-1), substr(str, pos+1));
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; end if;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; set pos = pos-1;
&amp;nbsp;&amp;nbsp;&amp;nbsp; end while;&amp;nbsp;&amp;nbsp; 

&amp;nbsp;&amp;nbsp; return str;
end //
delimiter ;&lt;/pre&gt;
&lt;br /&gt;
Execute as funcões acima em sua base de dados e faça o seguinte teste:&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #999999;&quot;&gt;select phonembr(&#39;casa&#39;);&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #999999;&quot;&gt;select phonembr(&#39;kasa&#39;);&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;color: #999999;&quot;&gt;select phonembr(&#39;caza&#39;);&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
como resultado as três consultas irá retornar KS, ou seja independente se a &lt;br /&gt;
palavra foi escrita com S, Z ou K o resultado será o mesmo.&lt;br /&gt;
&lt;br /&gt;
Bom galera este foi a implementação do algoritmo BuscaBR em MySQL, vou deixar um link da documentação do algoritmo &lt;a href=&quot;http://www.brunoportfolio.com/arquivos/pdf/BuscaBR_Fonetica.pdf&quot; target=&quot;_blank&quot;&gt;www.brunoportfolio.com/arquivos/pdf/BuscaBR_Fonetica.pdf&lt;/a&gt;. Espero que vocês tenham gostado, até a próxima.</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/6427342630996089935/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/6427342630996089935' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/6427342630996089935'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/6427342630996089935'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2013/02/implementando-algoritmo-buscabr-em-mysql.html' title='Implementando Algoritmo BuscaBR em MySQL'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgh_nrAM4Q9m7i0EDwPsUJbo1-LnX-tow6L5vtbd1a8jZWmuGS3nxs1FZmq46OA-u39iSLOHtdtbJbEt-a_t6cwFxCQAIUxpwwOhBXOxLDBwU7oNnnYVDoFHsk9o2DtkEt89rRvMiCY-yc/s72-c/MySQL.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-8184538663433985177</id><published>2011-11-08T14:05:00.003-02:00</published><updated>2011-11-16T14:42:32.668-02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript"/><title type='text'>Manipular Cookies com JavaScript</title><content type='html'>Olá galera, nesta postagem quero deixar um objeto em javascript com algumas funções para manipular cookies.&lt;br /&gt;
Logo abaixo deixei umm breve descrição de cada funcão e um exemplo de como utilizar.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Cookie.read&lt;/b&gt;&lt;br /&gt;
Le o valor de um cookie de acordo com o parâmetro passado&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Cookie.readJSON&lt;/b&gt;&lt;br /&gt;
Le o valor de um cookie no formato &lt;a href=&quot;http://www.json.org/&quot;&gt;JSON&lt;/a&gt; e retorna um objeto&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Cookie.readBool &lt;/b&gt;&lt;br /&gt;
Le o valor de um cookie de acordo com o parâmetro passado e retorna um tipo boolean&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Cookie.write&lt;/b&gt;&lt;br /&gt;
Grava um cookie, os parâmetros permitidos são o nome, valor e número de dias para expirar&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Cookie.clear&lt;/b&gt;&lt;br /&gt;
Limpa um cookie de acordo com o nome passado&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush:js&quot;&gt;Cookie = {
    read : function(name) {
        var regExp = new RegExp(name+&quot;=([^;]+)&quot;);
        var matches = regExp.exec(document.cookie);
        return matches ? matches[1] : null;
    },
    readJSON : function(name) {
        var value = this.read(name);
        return value != null ? new Function(&quot;return &quot;+value) : [];
    }, 
    readBool : function(name) {
        var value = this.read(name);
        return /^(true|t|1)$/i.test(value) ? true : (/^(false|f|0)$/i.test(value) ? false : null);
    }, 
    write : function(name, value, expireDays) {
        var date = new Date();
        var expires = &quot;&quot;;
        if (expireDays) {
            date.setTime(date.getTime() + (expireDays * 24 * 60 * 60 * 1000));
            expires = &quot;; expires=&quot;+date.toGMTString();
        }
        if (typeof(value) == &quot;object&quot;) value = ObjectUtils.json_encode(value);
            document.cookie = name+&quot;=&quot;+value+expires+&quot;;&quot;; 
            return document.cookie;  
        },
    clear : function(name) {
        var date = new Date();
        date.setTime(date.getTime() - 86400);
        document.cookie = name+&quot;=; expires=&quot;+date.toGMTString()+&quot;;&quot;;  
        return document.cookie; 
    }
};
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/8184538663433985177/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/8184538663433985177' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/8184538663433985177'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/8184538663433985177'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2011/11/cookie.html' title='Manipular Cookies com JavaScript'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-1605577483246038821</id><published>2011-08-08T14:58:00.003-03:00</published><updated>2011-08-16T18:57:18.231-03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="PHP"/><title type='text'>Remover caracteres especiais de uma String</title><content type='html'>Olá pessoal, nesta postagem quero deixar uma função simples de como remover os caracteres acentuados de uma String. É super simples de usar, basta apenas passar como parâmetro a String e o retorno será uma nova String sem os caracteres especiais.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: php&quot;&gt;function clear_special_char($input) {
    $search = array(&quot;\xC0&quot;, &quot;\xC1&quot;, &quot;\xC2&quot;, &quot;\xC3&quot;, &quot;\xC9&quot;, &quot;\xCA&quot;, &quot;\xCD&quot;, &quot;\xD3&quot;, &quot;\xD4&quot;, &quot;\xD5&quot;, &quot;\xDA&quot;, &quot;\xDC&quot;, &quot;\xC7&quot;, &quot;\xE0&quot;, &quot;\xE1&quot;, &quot;\xE2&quot;, &quot;\xE3&quot;, &quot;\xE9&quot;, &quot;\xEA&quot;, &quot;\xED&quot;, &quot;\xF3&quot;, &quot;\xF4&quot;, &quot;\xF5&quot;, &quot;\xFA&quot;, &quot;\xFC&quot;, &quot;\xE7&quot;);
    $replace = array(&quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;A&quot;, &quot;E&quot;, &quot;E&quot;, &quot;I&quot;, &quot;O&quot;, &quot;O&quot;, &quot;O&quot;, &quot;U&quot;, &quot;U&quot;, &quot;C&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;e&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;o&quot;, &quot;o&quot;, &quot;u&quot;, &quot;u&quot;, &quot;c&quot;);
    $string = str_replace($search, $replace, utf8_decode($input));
    return $string;
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/1605577483246038821/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/1605577483246038821' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/1605577483246038821'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/1605577483246038821'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2011/08/remover-caracteres-especiais-de-uma.html' title='Remover caracteres especiais de uma String'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-2689371524664495874</id><published>2011-08-04T14:25:00.009-03:00</published><updated>2011-08-05T20:41:54.121-03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript"/><title type='text'>Paleta de cores em JavaScript</title><content type='html'>&lt;div class=&quot;MsoNormal&quot;&gt;&lt;/div&gt;&lt;div class=&quot;MsoNormal&quot;&gt;Olá pessoal, nesta postagem quero deixar um tutorial de como montar uma paleta de cores utilizando JavaScript. Este recurso pode ser bem útil em algumas situações, abaixo tem um exemplo da função utilizada para gerar a paleta onde o primeiro parâmetro é o elemento que será utilizado para exibir a paleta de cores e o segundo é uma função de callback.&lt;br /&gt;
Espero que vocês gostem, e pode alterar o código conforme suas necessidades.&lt;/div&gt;&lt;br /&gt;
&lt;pre class=&quot;brush: js&quot;&gt;&amp;lt;script type=&quot;text/javascript&quot;&amp;gt;
function drawColorPalette(stageID, callback) {
    var listColor = [&quot;00&quot;, &quot;33&quot;, &quot;66&quot;, &quot;99&quot;, &quot;CC&quot;, &quot;FF&quot;];
    var table = document.createElement(&quot;table&quot;);
    table.border = 1;
    table.cellPadding = 0;
    table.cellSpacing = 0;
    table.style.borderColor = &quot;#666666&quot;;
    table.style.borderCollapse = &quot;collapse&quot;;
    var tr, td;
    var color = &quot;&quot;;
    var tbody = document.createElement(&quot;tbody&quot;);
    for (var i = 0; i &amp;lt; listColor.length; i++){
        tr = document.createElement(&quot;tr&quot;);
        for (var x = 0; x &amp;lt; listColor.length; x++) {
            for (var y = 0; y &amp;lt; listColor.length; y++) {
                color = &quot;#&quot;+listColor[i]+listColor[x]+listColor[y];
                td = document.createElement(&quot;td&quot;);
                td.style.width = &quot;11px&quot;;
                td.style.height = &quot;11px&quot;;
                td.style.background = color;
                td.color = color;
                td.style.borderColor = &quot;#000&quot;;
                td.style.cursor = &quot;pointer&quot;;
              
                if (typeof(callback) == &quot;function&quot;) {
                    td.onclick = function() {
                        callback.apply(this, [this.color]);
                    }
                }
                tr.appendChild(td); 
            }
        }
        tbody.appendChild(tr);
    }  
    table.appendChild(tbody);
    var element = document.getElementById(stageID);
    if (element) element.appendChild(table);
    return table;
}

window.onload = function() {
    drawColorPalette(&quot;mydiv&quot;, function(color) {
        document.getElementById(&quot;textcolor&quot;).innerHTML = color;
    }); 
}
&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;pre class=&quot;brush: js&quot;&gt;&amp;lt;div id=&quot;mydiv&quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;span id=&quot;textcolor&quot;&amp;gt;&amp;lt;/span&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Resultado gerado pelo exemplo acima:&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
function drawColorPalette(stageID, callback) {
 var listColor = [&quot;00&quot;, &quot;33&quot;, &quot;66&quot;, &quot;99&quot;, &quot;CC&quot;, &quot;FF&quot;];
 var table = document.createElement(&quot;table&quot;);
 table.border = 1;
 table.cellPadding = 0;
 table.cellSpacing = 0;
    table.style.borderColor = &quot;#666666&quot;;
 table.style.borderCollapse = &quot;collapse&quot;;
 var tr, td;
 var color = &quot;&quot;;
    var tbody = document.createElement(&quot;tbody&quot;);
 for (var i = 0; i &lt; listColor.length; i++){
  tr = document.createElement(&quot;tr&quot;);
  for (var x = 0; x &lt; listColor.length; x++) {
   for (var y = 0; y &lt; listColor.length; y++) {
    color = &quot;#&quot;+listColor[i]+listColor[x]+listColor[y];
    td = document.createElement(&quot;td&quot;);
    td.style.width = &quot;11px&quot;;
    td.style.height = &quot;11px&quot;;
    td.style.background = color;
    td.color = color;
                td.style.borderColor = &quot;#000&quot;;
                td.style.cursor = &quot;pointer&quot;;
              
                if (typeof(callback) == &quot;function&quot;) {
     td.onclick = function() {
      callback.apply(this, [this.color]);
     }
    }
    tr.appendChild(td); 
   }
  }
  tbody.appendChild(tr);
 }  
    table.appendChild(tbody);
 var element = document.getElementById(stageID);
    if (element) element.appendChild(table);
    return table;
}

window.onload = function() {
    drawColorPalette(&quot;mydiv&quot;, function(color) {
        document.getElementById(&quot;textcolor&quot;).innerHTML = color;
    }); 
}
&lt;/script&gt;




&lt;div id=&quot;mydiv&quot;&gt;

&lt;/div&gt;&lt;span id=&quot;textcolor&quot;&gt;&lt;/span&gt;</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/2689371524664495874/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/2689371524664495874' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/2689371524664495874'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/2689371524664495874'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2011/08/paleta-de-cores-em-javascript.html' title='Paleta de cores em JavaScript'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-314197607351632764</id><published>2011-07-31T18:26:00.001-03:00</published><updated>2011-07-31T18:26:48.360-03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="PHP"/><title type='text'>Valor por extenso com PHP</title><content type='html'>Nesta postagem quero compartilhar uma classe bem interessante, &quot;Monetary&quot;,&amp;nbsp; simplesmente ela formata um valor monetário por extenso. Logo abaixo segue o código da classe e um exemplo de como utilizar.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: php&quot;&gt;&amp;lt;?php
class Monetary {
    private static $unidades = array(&quot;um&quot;, &quot;dois&quot;, &quot;três&quot;, &quot;quatro&quot;, &quot;cinco&quot;, &quot;seis&quot;, &quot;sete&quot;, &quot;oito&quot;, &quot;nove&quot;, &quot;dez&quot;, &quot;onze&quot;, &quot;doze&quot;,
                                     &quot;treze&quot;, &quot;quatorze&quot;, &quot;quinze&quot;, &quot;dezesseis&quot;, &quot;dezessete&quot;, &quot;dezoito&quot;, &quot;dezenove&quot;);
    private static $dezenas = array(&quot;dez&quot;, &quot;vinte&quot;, &quot;trinta&quot;, &quot;quarenta&quot;,&quot;cinqüenta&quot;, &quot;sessenta&quot;, &quot;setenta&quot;, &quot;oitenta&quot;, &quot;noventa&quot;);
    private static $centenas = array(&quot;cem&quot;, &quot;duzentos&quot;, &quot;trezentos&quot;, &quot;quatrocentos&quot;, &quot;quinhentos&quot;, 
                                     &quot;seiscentos&quot;, &quot;setecentos&quot;, &quot;oitocentos&quot;, &quot;novecentos&quot;);
    private static $milhares = array(
        array(&quot;text&quot; =&amp;gt; &quot;mil&quot;, &quot;start&quot; =&amp;gt; 1000, &quot;end&quot; =&amp;gt; 999999, &quot;div&quot; =&amp;gt; 1000),
        array(&quot;text&quot; =&amp;gt; &quot;milhão&quot;, &quot;start&quot; =&amp;gt;  1000000, &quot;end&quot; =&amp;gt; 1999999, &quot;div&quot; =&amp;gt; 1000000),
        array(&quot;text&quot; =&amp;gt; &quot;milhões&quot;, &quot;start&quot; =&amp;gt; 2000000, &quot;end&quot; =&amp;gt; 999999999, &quot;div&quot; =&amp;gt; 1000000),
        array(&quot;text&quot; =&amp;gt; &quot;bilhão&quot;, &quot;start&quot; =&amp;gt; 1000000000, &quot;end&quot; =&amp;gt; 1999999999, &quot;div&quot; =&amp;gt; 1000000000),
        array(&quot;text&quot; =&amp;gt; &quot;bilhões&quot;, &quot;start&quot; =&amp;gt; 2000000000, &quot;end&quot; =&amp;gt; 2147483647, &quot;div&quot; =&amp;gt; 1000000000)        
    );
    const MIN = 0.01;
    const MAX = 2147483647.99;
    const MOEDA = &quot; real &quot;;
    const MOEDAS = &quot; reais &quot;;
    const CENTAVO = &quot; centavo &quot;;
    const CENTAVOS = &quot; centavos &quot;;    
    
    static function numberToExt($number, $moeda = true) {
        if ($number &amp;gt;= self::MIN &amp;amp;&amp;amp; $number &amp;lt;= self::MAX) {
            $value = self::conversionR((int)$number);       
            if ($moeda) {
                if (floor($number) == 1) {
                    $value .= self::MOEDA;
                }
                else if (floor($number) &amp;gt; 1) $value .= self::MOEDAS;
            }

            $decimals = self::extractDecimals($number);            
            if ($decimals &amp;gt; 0.00) {
                $decimals = round($decimals * 100);
                $value .= &quot; e &quot;.self::conversionR($decimals);
                if ($moeda) {
                    if ($decimals == 1) {
                        $value .= self::CENTAVO;
                    }   
                    else if ($decimals &amp;gt; 1) $value .= self::CENTAVOS;
                }
            }
        }
        return trim($value);
    }
    
    private static function extractDecimals($number) {
        return $number - floor($number);
    }
    
    static function conversionR($number) {
        if (in_array($number, range(1, 19))) {
            $value = self::$unidades[$number-1];
        }
        else if (in_array($number, range(20, 90, 10))) {
             $value = self::$dezenas[floor($number / 10)-1].&quot; &quot;;           
        }     
        else if (in_array($number, range(21, 99))) {
             $value = self::$dezenas[floor($number / 10)-1].&quot; e &quot;.self::conversionR($number % 10);           
        }     
        else if (in_array($number, range(100, 900, 100))) {
             $value = self::$centenas[floor($number / 100)-1].&quot; &quot;;           
        }          
        else if (in_array($number, range(101, 199))) {
             $value = &#39; cento e &#39;.self::conversionR($number % 100);         
        }   
        else if (in_array($number, range(201, 999))) {
             $value = self::$centenas[floor($number / 100)-1].&quot; e &quot;.self::conversionR($number % 100);        
        }  
        else {
            foreach (self::$milhares as $item) {
                if ($number &amp;gt;= $item[&#39;start&#39;] &amp;amp;&amp;amp; $number &amp;lt;= $item[&#39;end&#39;]) {
                    $value = self::conversionR(floor($number / $item[&#39;div&#39;])).&quot; &quot;.$item[&#39;text&#39;].&quot; &quot;.self::conversionR($number % $item[&#39;div&#39;]);
                    break;
                }
            }
        }        
        return $value;
    }
}

// exemplo de como utilizar
echo Monetary::numberToExt(4526.89);
// o exemplo acima ira imprimir: quatro mil quinhentos e vinte e seis reais e oitenta e nove centavos
?&amp;gt;
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/314197607351632764/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/314197607351632764' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/314197607351632764'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/314197607351632764'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2011/07/valor-por-extenso-com-php.html' title='Valor por extenso com PHP'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-3230333088972619634</id><published>2011-07-30T16:07:00.002-03:00</published><updated>2011-07-30T16:09:11.445-03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript"/><title type='text'>Setar posição do cursor com JavaScript</title><content type='html'>Neste post, quero compartilhar uma função que pode ser bem útil, trata-se de uma solução de como setar o cursor em um determinado ponto de um input text ou textarea. Esta função foi testada no Firefox, IE 7 e Chrome.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: js&quot;&gt;function setPosCursor(element, pos) {
    element.focus();
    if (typeof(element.setSelectionRange) != &quot;undefined&quot;) {
        element.setSelectionRange(pos, pos);
    }
    else if (element.createTextRange) {
        var breaks = element.value.slice(0, pos).match(/\n/g);
        var endPoint = 0;
        if (breaks instanceof Array) {
            endPoint = -breaks.length;
        }
        var range = element.createTextRange(); 
        range.collapse(true); 
        range.moveStart(&quot;character&quot;, pos); 
        range.moveEnd(&quot;character&quot;, endPoint); 
        range.select(); 
    }
} 
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/3230333088972619634/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/3230333088972619634' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/3230333088972619634'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/3230333088972619634'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2011/07/setar-posicao-do-cursor-com-javascript.html' title='Setar posição do cursor com JavaScript'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-7868845412864903500</id><published>2011-07-30T00:53:00.003-03:00</published><updated>2011-07-30T15:55:30.647-03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="JavaScript"/><title type='text'>Pegar posição do cursor com JavaScript</title><content type='html'>Em algumas situações precisamos pegar a posição do cursor em um campo de texto (aquele que fica piscando), abaixo tenho uma solução bem prática eu testei no Firefox, IE 7 e Chrome. Para utilizar, você deve passar o elemento input text ou textarea como parâmetro o retorno será um inteiro com o índice da posição.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: js;&quot;&gt;function getPosCursor(element) {
    var value = 0;
    if (typeof(element.selectionStart) != &quot;undefined&quot;) {
        value = element.selectionStart;
    }
    else if (document.selection) {
        var range = document.selection.createRange();
        var storedRange = range.duplicate();
        storedRange.moveToElementText(element);
        storedRange.setEndPoint(&quot;EndToEnd&quot;, range);
        value = storedRange.text.length - range.text.length;
    }
    return value;
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/7868845412864903500/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/7868845412864903500' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/7868845412864903500'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/7868845412864903500'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2011/07/pegar-posicao-do-cursor-com-javascript.html' title='Pegar posição do cursor com JavaScript'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3692489238488225957.post-7031748799141946886</id><published>2011-07-29T14:53:00.021-03:00</published><updated>2011-07-30T15:38:23.333-03:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="PHP"/><title type='text'>Envio de e-mail com PHP por Socket</title><content type='html'>Para o envio de e-mail o PHP nos possibilita o uso da função &lt;a href=&quot;http://php.net/mail&quot;&gt;&lt;b&gt;mail&lt;/b&gt;&lt;/a&gt;, porém para utilizá-la é preciso efetuar algumas configurações no php.ini e esta função é bem limitada quanto a servidores SMTP que requerem autenticação com usuário e senha. Neste tutorial estarei ensinando como enviar e-mail por Socket utilizando a função &lt;b&gt;&lt;a href=&quot;http://php.net/fsockopen&quot;&gt;fsockopen&lt;/a&gt;&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
Abaixo tem a função com o exemplo de utilização, espero que vocês gostem e qualquer dúvida é só comentar.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: php;&quot;&gt;&amp;lt;?php
function enviar_email($destinatario, $remetente, $assunto, $mensagem) {
    // dominio do servidor SMTP, para servidores HTTPS coloque o prefixo ssl://
    $servidor = &quot;smtp.meuservidor.com&quot;;
    // usuario do servidor SMTP
    $usuario = &quot;usuario&quot;;
    // senha do servidor SMTP
    $senha = &quot;senha&quot;;
    // numero da porta do servidor SMTP
    $success = true;
        
    // abro uma conexao por socket com o servidor
    $socket = @fsockopen($servidor, 25, $errno, $errstr, 10);
    if ($socket) {
        $ln = &quot;\r\n&quot;; 
        // pego o texto de retorno do servidor e verifico o codigo da resposta se for 220 ok
        $response = fgets($socket, 256);
        if (!preg_match(&quot;/^220/&quot;, $response)) $success = false;

        // envio um comando HELO e verifico o codigo da resposta se for 250 ok
        fwrite($socket, &quot;HELO $servidor&quot;.$ln);
        $response = fgets($socket, 256);
        if (!preg_match(&quot;/^250/&quot;, $response)) $success = false;
       
        // envio um comando AUTH LOGIN para iniciar a autenticacao
        fwrite($socket, &quot;AUTH LOGIN&quot;.$ln);
        fgets($socket, 256);
        // envio o nome de usuario
        fwrite($socket, base64_encode($usuario).$ln);
        fgets($socket, 256);
        // envio senha do servidor
        fwrite($socket, base64_encode($senha).$ln);
        // verifico o codigo da resposta se for 235 a autenticacao ocorreu com sucesso
        $response = fgets($socket, 256);
        if (!preg_match(&quot;/^235/&quot;, $response)) $success = false;

        // envio um comando MAIL FROM e verifico o codigo da resposta se for 250 ok      
        fwrite($socket, &quot;MAIL FROM:$remetente&quot;.$ln);
        $response = fgets($socket, 256); 
        if (!preg_match(&quot;/^250/&quot;, $response)) $success = false;
        
        // envio um comando RCPT TO e verifico o codigo da resposta se for 250 ok 
        fwrite($socket, &quot;RCPT TO:$destinatario&quot;.$ln);
        $response = fgets($socket, 256);
        if (!preg_match(&quot;/^250/&quot;, $response)) $success = false;

        // envio um comando DATA e verifico o codigo da resposta se for 354 ok 
        fwrite($socket, &quot;DATA&quot;.$ln);
        $response = fgets($socket, 256);
        if (!preg_match(&quot;/^354/&quot;, $response)) $success = false;
        
        // definicao dos cabecalhos da mensagem 
        $headers = &quot;Message-Id: &amp;lt;&quot;.time().&quot;.&quot;.md5(microtime()).&quot;@&quot;.$_SERVER[&#39;SERVER_ADDR&#39;].&quot;&amp;gt;&quot;.$ln;
        $headers .= &quot;Date: &quot;.date(&quot;r&quot;).$ln;
        $headers .= &quot;X-Priority: 3&quot;.$ln;
        $headers .= &quot;Content-Type: text/plain; charset=\&quot;UTF-8\&quot;&quot;.$ln;
        $headers .= &quot;Subject: $assunto&quot;.$ln;
        $headers .= &quot;To: $destinatario&quot;.$ln;       
        $headers .= &quot;From: $remetente&quot;.$ln.$ln;
        $headers .= $mensagem.$ln.&quot;.&quot;.$ln;
        fwrite($socket, $headers);
        $response = fgets($socket, 256);
        if (!preg_match(&quot;/^250/&quot;, $response)) $success = false;
 
         // envio um comando QUIT e verifico o codigo da resposta se for 221 ok        
        fwrite($socket, &quot;QUIT&quot;.$ln);
        $response = fgets($socket, 256);
        if (!preg_match(&quot;/^221/&quot;, $response)) $success = false;
        
        // fecho a conexao com o servidor
        fclose($socket);
        return $success;
    }
    else return false;
}

$result = enviar_email(&quot;destinatario@email.com&quot;, &quot;remetente@email.com&quot;, &quot;Meu Assunto&quot;, &quot;Minha Mensagem&quot;);
if ($result) {
    echo &quot;E-mail enviado com sucesso!&quot;;
}
else echo &quot;Ocorreu um erro ao tentar enviar o e-mail!&quot;;
?&amp;gt;
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://extremoconhecimento.blogspot.com/feeds/7031748799141946886/comments/default' title='Postar comentários'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment/fullpage/post/3692489238488225957/7031748799141946886' title='0 Comentários'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/7031748799141946886'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3692489238488225957/posts/default/7031748799141946886'/><link rel='alternate' type='text/html' href='http://extremoconhecimento.blogspot.com/2011/07/envio-de-e-mail-por-socket-com-php.html' title='Envio de e-mail com PHP por Socket'/><author><name>Bruno P. Sousa</name><uri>http://www.blogger.com/profile/13913070144357788319</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>