<?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>Arthur Sorriso &#187; PHP</title>
	<atom:link href="http://www.arthursorriso.com.br/index.php/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.arthursorriso.com.br</link>
	<description>Só mais um blog... Será?!</description>
	<lastBuildDate>Sat, 30 Jan 2010 15:36:15 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Tutorial PHP &#8211; Sistema de Login Utilizando Sessões</title>
		<link>http://www.arthursorriso.com.br/index.php/tutorial-php-sistema-de-login-utilizando-sessoes/</link>
		<comments>http://www.arthursorriso.com.br/index.php/tutorial-php-sistema-de-login-utilizando-sessoes/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 20:17:29 +0000</pubDate>
		<dc:creator>arthur</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[Programaçã]]></category>
		<category><![CDATA[Sessões]]></category>
		<category><![CDATA[Sistema de Login]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.arthursorriso.com.br/?p=377</guid>
		<description><![CDATA[Neste tutorial mostrarei como fazer um simples sistema de login de usuário, utilizando sessões, e com consultas ao banco de dados.]]></description>
			<content:encoded><![CDATA[<p>Dando continuiade aos tutorias de PHP, vou mostrar agora como criar um sistema de login de usuário, conectando com o banco de dados MySQL, e gravando os dados em Sessões.</p>
<p>Primeiramente, você deverá ter um servidor com suporte PHP instalado em seu computador, ou então alguma hospedagem, para testar a aplicação. Se desejar instalar um servidor e não souber como, leia o <a href="http://www.arthursorriso.com.br/index.php/tutorial-php-instalacao-do-servidor-easyphp-apache-php-mysql/">tutorial de instalação do EasyPHP</a> que escrevi a alguns meses.</p>
<p>Vamos começar!</p>
<p>Primeiramente, crie o banco de dados. No nosso caso escolhi o nome &#8220;tutoriais&#8221;, pois irei utilizá-lo em outros artigos.</p>
<p>Depois que o banco estiver criado, o próximo passo é criar a tabela de usuarios.</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">CREATE</span> <span style="color: #993333; font-weight: bold;">TABLE</span> <span style="color: #993333; font-weight: bold;">IF</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">EXISTS</span> <span style="color: #ff0000;">`usuario`</span> <span style="color: #66cc66;">&#40;</span>
  <span style="color: #ff0000;">`id`</span> int<span style="color: #66cc66;">&#40;</span>6<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span> <span style="color: #993333; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`nome`</span> varchar<span style="color: #66cc66;">&#40;</span>255<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`login`</span> varchar<span style="color: #66cc66;">&#40;</span>255<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #ff0000;">`senha`</span> varchar<span style="color: #66cc66;">&#40;</span>255<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">NOT</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">,</span>
  <span style="color: #993333; font-weight: bold;">PRIMARY</span> <span style="color: #993333; font-weight: bold;">KEY</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`id`</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>Com a tabela criada, vamos agora povoá-la:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> <span style="color: #ff0000;">`usuario`</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">`id`</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`nome`</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`login`</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">`senha`</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'Arthur Sorriso'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'sorriso'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'698dc19d489c4e4db73e28a713eab07b'</span><span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>O campo senha, está encriptado no formato MD5, para uma melhor segurança. Aqui ela significa apenas &#8220;teste&#8221;.</p>
<p>Agora, o próximo passo é criar o formulário de login.</p>
<p>form_login.php</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;strong&gt;Sistema de Login&lt;/strong&gt;
&lt;form action=&quot;autenticar.php&quot; method=&quot;post&quot;&gt;
Login: &lt;input name=&quot;login&quot; type=&quot;text&quot; /&gt;
Senha: &lt;input name=&quot;senha&quot; type=&quot;password&quot; /&gt;
&lt;input type=&quot;submit&quot; value=&quot;Acessar&quot; /&gt;&lt;/form&gt;</pre></div></div>

<p>Explicando o código:</p>
<p>A primeira linha é apenas um título, para ficar organizado. Nada de mais.</p>
<p>Na segunda começamos a criar o formulário. Utilizamos a tag form. O parâmetro action informa o destino que a página vai quando o botão &#8220;Acessar&#8221; é presionado. O parâmetro &#8220;method&#8221; pode ser &#8220;get&#8221; ou &#8220;post&#8221;. Para este utilizaremos &#8220;post&#8221; por ser mais seguro. No &#8220;get&#8221;, os dados do formulário serão enviados via endereço no browser, o que não queremos.</p>
<p>Na terceira linha criaremos o campo para o usuário digitar o login. Para isso utilizamos a tag &#8220;input&#8221; com tipo texto.</p>
<p>Na quarta linha criaremos o campo para senha. É análogo ao campo de login, a única diferença é o tipo, que agora passa a ser &#8220;password&#8221; de forma que quando o usuário digitar algo, isto aparecerar como asterisco(*).</p>
<p>Na quinta linha criaremos o botão para submeter o nosso formulário. Para isso utilizamos a tag &#8220;input&#8221; com tipo &#8220;submit&#8221;. E depois fechamos o formulário.</p>
<p>Vamos agora criar a página que fará a conexão com o nosso banco de dados.<br />
connect.php</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;">$host</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;localhost&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;root&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$password</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$dbname</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;tutoriais&quot;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">mysql_connect</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$host</span><span style="color: #339933;">,</span> <span style="color: #000088;">$user</span><span style="color: #339933;">,</span> <span style="color: #000088;">$password</span><span style="color: #009900;">&#41;</span> or <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao tentar se conectar!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">mysql_select_db</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$dbname</span><span style="color: #009900;">&#41;</span>or <span style="color: #990000;">die</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Erro ao selecionar o banco!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Explicando o código:</p>
<p>Primeiramente pegamos as variáveis necessárias para a conexão no banco de dados. A primeira é o host para conectar. Na maioria dos casos será localhost mesmo. Depois usuário e senha do banco de dados. E por último o banco de dados que será utilizado. Como falei lá em cima, o banco que utilizarei é o tutoriais.</p>
<p>Depois criaremos a nossa conexão. Para isso utilizaremos a função mysql_connect e passaremos como parâmetros as variáveis de cima. Caso ocorra um erro, será mostrada a mensagem escrita dentro do die().</p>
<p>Por fim fazemos a seleção do banco de dados que iremos utilizar.<br />
Simples.</p>
<p>Agora vamos para a parte mais complicada, mas não difícil, do tutorial. A página que será responsável pela autenticação do usuário, criando assim sua sessão.</p>
<p>autenticar.php</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;connect.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Recebendo os dados do formulário</span>
<span style="color: #000088;">$login</span> <span style="color: #339933;">=</span> <span style="color: #990000;">addslashes</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;login&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$senha</span> <span style="color: #339933;">=</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">addslashes</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;senha&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$sql</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT * FROM usuario WHERE login = '<span style="color: #006699; font-weight: bold;">$login</span>' AND senha = '<span style="color: #006699; font-weight: bold;">$senha</span>'&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$rs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$sql</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">mysql_num_rows</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$rs</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> 1<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_fetch_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$rs</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #666666; font-style: italic;">//conferindo o login e senha para segurança</span>
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$login</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$user</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'login'</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;">//se entrou, entao o login é igual</span>
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$senha</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$user</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'senha'</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;">//se entrou, então a senha também é igual</span>
			<span style="color: #000088;">$logado</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;1&quot;</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$id_user</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #666666; font-style: italic;">//criando a sessão</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>
			<span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;id_user&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$id_user</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;logado&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logado</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #666666; font-style: italic;">//depois que criarmos a sessão, </span>
                        <span style="color: #666666; font-style: italic;">//vamos redirecionar para a página privada</span>
			<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Location: cadastro.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;A senha não confere!&quot;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;O usuário não confere!&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Usuário ou senha inválidos. Tente novamente.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Explicando o código:</p>
<p>Primeiramente incluimos o arquivo connect.php, a fim de estabelecermos a conexão com o banco de dados.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Recebendo os dados do formulário</span>
<span style="color: #000088;">$login</span> <span style="color: #339933;">=</span> <span style="color: #990000;">addslashes</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;login&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$senha</span> <span style="color: #339933;">=</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">addslashes</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;senha&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Depois iremos receber as variáveis passadas pelo formulário. A função addslashes() serve para tratarmos nossas Strings recebidas, afim de evitar qualquer ataque de Sql Injection. Ela funciona da seguinte forma: sempre que encontrar qualquer aspa simples (&#8217;) ou dupla (&#8221;), ele adiciona uma barra invertida antes dela, ficando por exemplo \&#8217;. Uma das formas de invasão de sites mais simples é esta, digitando por exemplo &#8216;or 1=1 &#8211;. Esta é uma forma de se evitar. Continuando, a função md5() serve para encriptar a senha, já que a do banco está encriptada, a que se passa no formulário deverá também o ser, para comparamos.</p>
<p>Na próxima criamos uma variável para receber nossa string sql. Ela seleciona tudo (*) da tabela usuario, onde o login for igual ao da variável e a senha também. Simples.</p>
<p>Na próxima linha executamos o sql.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$sql</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT * FROM usuario WHERE login = '<span style="color: #006699; font-weight: bold;">$login</span>' AND senha = '<span style="color: #006699; font-weight: bold;">$senha</span>'&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$rs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$sql</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;">mysql_num_rows</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$rs</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span></pre></div></div>

<p>A seguir, testamos se o comando retornou alguma linha na consulta. Se não, o usuário e a senha poderá ter sido escrito errado, ou até mesmo não existir.</p>
<p>Se a consulta estiver correta, entraremos no nosso if.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_fetch_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$rs</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//conferindo o login e senha para segurança</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$login</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$user</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'login'</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;">//se entrou, entao o login é igual</span>
	<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$senha</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$user</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'senha'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span></pre></div></div>

<p>A primeira linha dentro do if cria um array na variável $user com os dados coletados no banco de dados.</p>
<p>A seguir, conferimos se o conteúdo da variável é igual ao conteúdo vindo pelo formulário, evitando assim também alguma invasão.</p>
<p>Depois de conferidos o usuário e a senha, iremos ao próximo trecho:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//se entrou, então a senha também é igual</span>
<span style="color: #000088;">$logado</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;1&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$id_user</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//criando a sessão</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>
<span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;id_user&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$id_user</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">&quot;logado&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$logado</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">//depois que criarmos a sessão, vamos redirecionar para a página privada</span>
<span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Location: cadastro.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Primeiramente atribuimos o valor 1 à variável $logado, já que o usuário escreveu tudo corretamente, e depois guardamos o id do usuário no banco na variável $id_user.</p>
<p>Agora podemos criar nossa sessão inicializando ela primeiramente, e depois criando suas variáveis.</p>
<p>A seguir, redirecionamos à página que queremos que os usuários logados acessem.</p>
<p>As próximas linhas são apenas fechamentos dos ifs e tratamentos de erros, com os elses.</p>
<p>Agora iremos para a nossa página privada, que só poderá ter seu conteúdo visto se o usuário estiver logado.</p>
<p>cadastro.php</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: #666666; font-style: italic;">//Iniciando a sessão</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>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;connect.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'logado'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> 1<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$sql</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT * FROM usuario WHERE id = &quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id_user'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$rs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$sql</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;">mysql_num_rows</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$rs</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_fetch_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$rs</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;strong&gt; Olá &quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$user</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'nome'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;!&lt;/strong&gt; &quot;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;a href=&quot;</span>logout<span style="color: #339933;">.</span>php<span style="color: #0000ff;">&quot;&gt;Sair&lt;/a&gt;&quot;</span><span style="color: #339933;">;</span>
		<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Esta é sua página privada. 
                Nos próximos tutoriais continuaremos com esta página.&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Você não está logado. Tudo está oculto para você!&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Explicando o código:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">session_start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;connect.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'logado'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span></pre></div></div>

<p>Nas primeiras linhas iniciamos a nossa sessão, e incluímos o arquivo de conexão com o banco. A seguir testamos se usuário está realmente logado, vendo se o conteúdo da variável de sessão $_SESSION['logado'] é igual a 1, conforme definimos no arquivo autenticar.php.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$sql</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT * FROM usuario WHERE id = &quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id_user'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$rs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$sql</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;">mysql_num_rows</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$rs</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_fetch_array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$rs</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;strong&gt; Olá &quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$user</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'nome'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;!&lt;/strong&gt; &quot;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;a href=&quot;</span>logout<span style="color: #339933;">.</span>php<span style="color: #0000ff;">&quot;&gt;Sair&lt;/a&gt;&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Esta é sua página privada. 
        Nos próximos tutoriais continuaremos com esta página.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Agora escrevemos o nosso conteúdo oculto a não logados. Aqui fiz apenas uma simples consulta para pegar o nome do usuário, e exibí-lo nas boas vindas. Em seguida, apresentei o link para o usuário se deslogar do sistema.</p>
<p>O restante do código é apenas fechamento de if, e um else para os usuários não logados.</p>
<p>Por fim, a página de logout.</p>
<p>logout.php</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: #666666; font-style: italic;">//Iniciando a sessão</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>
<span style="color: #666666; font-style: italic;">//destruindo a sessão</span>
<span style="color: #990000;">session_destroy</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">Header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Location: form_login.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Nela nós destruimos a sessão, e redirecionamos para a página de login.</p>
<p>No próximo tutorial, irei abordar a parte de inserção no banco de dados. Pretendo fazê-lo como uma continuação deste, modificando nossa página cadastro.php, a fim de cadastrar novos usuários.</p>
<p>Bom por hoje é só. Espero ter sido claro no tutorial.</p>
<p>Se tiverem dúvidas é só perguntar nos comentários.</p>
<p><strong><a href = "http://www.arthursorriso.com.br/wp-content/uploads/2009/06/login.zip">Arquivos do artigo para download</a></strong></p>
<p>Abraço.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arthursorriso.com.br/index.php/tutorial-php-sistema-de-login-utilizando-sessoes/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
		<item>
		<title>Tutorial PHP &#8211; Instalação do Servidor &#8211; EasyPHP (Apache/PHP/Mysql)</title>
		<link>http://www.arthursorriso.com.br/index.php/tutorial-php-instalacao-do-servidor-easyphp-apache-php-mysql/</link>
		<comments>http://www.arthursorriso.com.br/index.php/tutorial-php-instalacao-do-servidor-easyphp-apache-php-mysql/#comments</comments>
		<pubDate>Mon, 02 Feb 2009 04:45:30 +0000</pubDate>
		<dc:creator>arthur</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[EasyPHP]]></category>
		<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHPMyAdmin]]></category>
		<category><![CDATA[Servidor]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.arthursorriso.com.br/?p=290</guid>
		<description><![CDATA[O começo de uma série de tutoriais envolvendo a linguagem de programação para Web PHP. A primeira parte trata da instalação do servidor, no nosso caso, o EasyPHP.]]></description>
			<content:encoded><![CDATA[<p>Fala galera!</p>
<p>Irei começar uma série quase infinita (não sei até quando ou onde vai) de tutoriais para aqueles interessados em aprender a linguagem de programação para Web <a href="http://www.php.net" target="_blank">PHP</a>.</p>
<p><img class="aligncenter size-full wp-image-291" title="PHP Hello World" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/php.jpg" alt="" width="300" height="100" /></p>
<p><span id="more-290"></span></p>
<p>As principais características do PHP são:</p>
<ul>
<li>Velocidade e robustez;</li>
<li>Estruturado e orientado a objeto;</li>
<li>Portabilidade &#8211; roda em qualquer lugar;</li>
<li>Tipagem fraca;</li>
<li>Sintaxe similar a C/C++.</li>
</ul>
<h3>Instalação do Servidor</h3>
<p>Para que possamos executar nossas páginas e códigos PHP em nosso computador, temos que ter um servidor instalado. Para isso utilizaremos neste tutorial o EasyPHP.</p>
<p>O EasyPHP é uma ferramenta que monta um Servidor Web em sua máquina com Apache, PHP e MySQL. Com algumas configurações a mais poderemos adicionar outros Bancos de dados, como o PostgreSQL por exemplo.</p>
<p>Para baixar o EasyPHP em sua versão mais recente, a 3.0, clique <a href="http://sourceforge.net/project/showfiles.php?group_id=14045" target="_blank">AQUI</a>.</p>
<p>Como qualquer instalação do Windows, ela consiste apenas em Aceitar e Próximo.</p>
<p>Execute o arquivo EasyPHP-3.0-setup.exe.</p>
<p>Primeiramente selecione o idioma para a instalação, como mostra a figura abaixo:</p>
<p><img class="aligncenter size-full wp-image-292" title="easy01" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy01.jpg" alt="" width="305" height="153" /></p>
<p>A tela de boas vindas será apresentada, com algumas recomendações. Clique em <strong>avançar</strong>.</p>
<p><img class="aligncenter size-full wp-image-293" title="easy02" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy02.jpg" alt="" width="483" height="370" /></p>
<p>A tela seguinte trás o contrato de licença de uso. Se costuma ler, vá em frente. Se concordar, basta <strong>aceitar</strong> e <strong>avançar</strong> para prosseguir com a instalação.</p>
<p><img class="aligncenter size-full wp-image-294" title="easy03" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy03.jpg" alt="" width="485" height="373" /></p>
<p>A próxima tela trás algumas advertências como fazer um backup dos arquivos caso tenha outra versão instalada, fechar a mesma se estiver aberta, entre outras coisas. Quando estiver pronto clique em <strong>avançar</strong>.</p>
<p><img class="aligncenter size-full wp-image-295" title="easy04" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy04.jpg" alt="" width="483" height="371" /></p>
<p>Neste próximo passo você poderá escolher onde o EasyPHP será instalado. Normalmente deixa-se como está. Ao final, clique em <strong>avançar</strong>.</p>
<p><img class="aligncenter size-full wp-image-296" title="easy05" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy05.jpg" alt="" width="483" height="373" /></p>
<p>A próxima tela apenas mostra como aparecerá no Menu Iniciar. Deixe como está e clique em <strong>avançar</strong>.</p>
<p><img class="aligncenter size-full wp-image-297" title="easy06" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy06.jpg" alt="" width="482" height="372" /></p>
<p>A tela seguinte mostra como será instalado, de acordo com as configurações que você escolheu, como o local onde será instalado e o atalho no Menu Iniciar. Clique em <strong>instalar</strong> para começar a instalação.</p>
<p><img class="aligncenter size-full wp-image-298" title="easy07" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy07.jpg" alt="" width="484" height="371" /></p>
<p>Agora a instalação está em curso. Aguarde enquanto a barra de progresso é completada.</p>
<p><img class="aligncenter size-full wp-image-299" title="easy08" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy08.jpg" alt="" width="479" height="366" /></p>
<p>Pronto! Você agora tem o EasyPHP instalado em seu computador. Clique em <strong>concluir</strong> para finalizar a instalação.</p>
<p><img class="aligncenter size-full wp-image-300" title="easy09" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/easy09.jpg" alt="" width="479" height="367" /></p>
<p>Junto com o EasyPHP vem o PHPMyAdmin. Este sistema serve para facilitar no uso do SGBD MySQL. Para utilizá-lo entre no diretório em que você instalou o EasyPHP (se não tiver mudado nada na instalação está em C:\Arquivos de Programas\EasyPHP 3.0). Lá, você encontrará o diretório phpmyadmin. Arraste-o para www e pronto.</p>
<p>Para executar o EasyPHP é simples. Basta procurá-lo no Menu Iniciar, e executar. Repare que o ícone do EasyPHP irá aparecer ao lado do relógio, na barra de tarefas. Clicando com o botão direito nele é possível ver todas opções e configurações.</p>
<p>Se tudo estiver bem, ao posicionar o Mouse em cima do ícone o texto &#8220;EasyPHP (Iniciado)&#8221; será apresentado. Caso contrário, basta clicar com o botão esquerdo do Mouse, e tentar iniciar os serviços que estiverem parados.</p>
<p>Uma vez executado, abra o seu navegador, e digite na barra de endereços http://localhost.</p>
<p>Todo o conteúdo que está na pasta www será apresentado em forma de lista, como mostrado a seguir:</p>
<p><img class="aligncenter size-full wp-image-301" title="local" src="http://www.arthursorriso.com.br/wp-content/uploads/2009/02/local.jpg" alt="" width="365" height="111" /></p>
<p>Como por enquanto só temos a pasta do phpmyadmin no nosso servidor, somente ela será apresentada.</p>
<p>Agora você possui um servidor web com Apache, PHP e MySQL instalado em seu computador. Sempre que for escrever alguma página ou script PHP, salve o conteúdo na pasta www, execute o EasyPHP, e escreva localhost em seu navegador para testa-lo.</p>
<p>Espero ter sido claro no tutorial. Nos próximos pularemos toda essa parte introdutória, portanto, prestem atenção neste. <img src='http://www.arthursorriso.com.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Dúvidas, é só utilizar os comentários.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arthursorriso.com.br/index.php/tutorial-php-instalacao-do-servidor-easyphp-apache-php-mysql/feed/</wfw:commentRss>
		<slash:comments>81</slash:comments>
		</item>
		<item>
		<title>Tutorial PHP &#8211; Script de previsão do tempo</title>
		<link>http://www.arthursorriso.com.br/index.php/tutorial-php-script-de-previsao-do-tempo/</link>
		<comments>http://www.arthursorriso.com.br/index.php/tutorial-php-script-de-previsao-do-tempo/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 23:11:47 +0000</pubDate>
		<dc:creator>arthur</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Previsão do Tempo]]></category>
		<category><![CDATA[Software Livre]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[Script]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.arthursorriso.com.br/?p=111</guid>
		<description><![CDATA[Bem, como alguns já sabem, o topo deste blog muda constantemente de paisagem de acordo com a previsão do tempo de minha cidade (Natal/RN). Mas como fiz isso? PHP!
A seguir detalho os passos&#8230;
Primeiramente veremos de onde pegar as informações do tempo. Escolhi o tempoagora, pois ao fim do endereço insere-se a cidade de onde deseja [...]]]></description>
			<content:encoded><![CDATA[<p>Bem, como alguns já sabem, o topo deste blog muda constantemente de paisagem de acordo com a previsão do tempo de minha cidade (Natal/RN). Mas como fiz isso? PHP!</p>
<p>A seguir detalho os passos&#8230;</p>
<p>Primeiramente veremos de onde pegar as informações do tempo. Escolhi o <a href="http://tempoagora.uol.com.br/" target="_blank">tempoagora</a>, pois ao fim do endereço insere-se a cidade de onde deseja buscar a previsão, facilitando assim nosso trabalho.</p>
<p>No meu caso seria <em>http://tempoagora.uol.com.br/previsaodotempo.html/brasil/</em><strong><em>Natal-RN</em></strong>.</p>
<p>Agora vamos ao que interessa.<br />
<span id="more-111"></span><br />
O Script completo desse tutorial fica assim:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"> <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>?php
   <span style="color: #666666; font-style: italic;">//Definimos a cidade</span>
   <span style="color: #000088;">$cidade</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Natal-RN'</span><span style="color: #339933;">;</span>
   <span style="color: #666666; font-style: italic;">//Capturamos o conteudo do site</span>
   <span style="color: #000088;">$file</span> <span style="color: #339933;">=</span> <span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;http://tempoagora.uol.com.br/previsaodotempo.html/brasil/&quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$cidade</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">//Capturamos a imagem</span>
   <span style="color: #000088;">$img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">explode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;mini-&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$file</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000088;">$img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">explode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;.gif&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$img</span><span style="color: #009900;">&#91;</span>2<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>         
&nbsp;
   <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$img</span><span style="color: #009900;">&#91;</span>0<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'PI'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Pouco ensolarado&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'CC'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Céu Claro&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'PC'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Pancadas de chuva&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'NC'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Nublado com chuva&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'CH'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Chuvoso&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'NB'</span><span style="color: #339933;">:</span>	  <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Nublado&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'PN'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Poucas núvens&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>     <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Céu claro&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
?<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span></pre></div></div>

<p>Agora vamos às explicações&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">   <span style="color: #666666; font-style: italic;">//Definimos a cidade</span>
   <span style="color: #000088;">$cidade</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'Natal-RN'</span><span style="color: #339933;">;</span>
   <span style="color: #666666; font-style: italic;">//Capturamos o conteudo do site</span>
   <span style="color: #000088;">$file</span> <span style="color: #339933;">=</span> <span style="color: #990000;">file_get_contents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;http://tempoagora.uol.com.br/previsaodotempo.html/brasil/&quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$cidade</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Neste trecho de código, primeiramente, definimos a cidade à qual estamos interessados em saber a previsão do tempo. A seguir, utilizando-se da função <a href="http://br.php.net/file_get_contents" target="_blank">file_get_contents</a>, capturamos o conteúdo da página como um arquivo. Repare que a variável $cidade aparece concatenada em seguida com o endereço, completando assim o mesmo.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">   <span style="color: #666666; font-style: italic;">//Dividimos o conteudo em partes</span>
   <span style="color: #000088;">$sep</span> <span style="color: #339933;">=</span> <span style="color: #990000;">explode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;&amp;amp;deg;C&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$file</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">//Capturamos a imagem</span>
   <span style="color: #000088;">$img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">explode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;mini-&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$file</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000088;">$img</span> <span style="color: #339933;">=</span> <span style="color: #990000;">explode</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;.gif&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$img</span><span style="color: #009900;">&#91;</span>2<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>De posse dos dados do conteúdo site na variável $file, iremos tratá-lo agora. Com o site aberto, percebemos que uma imagem é apresentada, com o desenho da previsão (como neste site). É em cima dela que iremos trabalhar.</p>
<p>Clicando em &#8216;exibir imagem&#8217; com o botão direito vemos que o endereço segue um padrão, como por exemplo mini-NB.gif, para nublado. E é isso que vem depois do &#8216;mini-&#8217; que irá nos interessar.</p>
<p>Com o auxílio da função <a href="http://br.php.net/manual/pt_BR/function.explode.php" target="_blank">explode</a>, quebramos o conteúdo de $file cada vez que aparecer &#8216;mini-&#8217;, e depois fazemos outro explode, mas dessa vez com $img[2], cada vez que encontrarmos &#8216;.gif&#8217;, que é para restar apenas as duas letras correspondentes à previsão, como &#8216;NB&#8217; por exemplo.</p>
<p>Pronto! Agora para finalizar:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">   <span style="color: #b1b100;">switch</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$img</span><span style="color: #009900;">&#91;</span>0<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'PI'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Pouco ensolarado&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'CC'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Céu Claro&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'PC'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Pancadas de chuva&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'NC'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Nublado com chuva&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'CH'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Chuvoso&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'NB'</span><span style="color: #339933;">:</span>	  <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Nublado&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">case</span> <span style="color: #0000ff;">'PN'</span><span style="color: #339933;">:</span>   <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Poucas núvens&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>     <span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Céu claro&quot;</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span></pre></div></div>

<p>No passo anterior fizemos um explode na imagem, e gravamos o resultado na variável $img. Esta variável é um vetor de Strings, e se imprimirmos a posição zero desse vetor, teremos o resultado que desejamos.</p>
<p>Todas as possíveis situações são: PI, CC, PC, NC, CH, NB e PN. Como podem ver, fiz apenas um switch com $img[0], mas vocês podem adaptar da forma que desejarem.</p>
<p>Bom isso é só. Espero ter explicado direitinho.</p>
<p>Quaisquer dúvidas, podem perguntar nos comentários. Estarei à disposição.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arthursorriso.com.br/index.php/tutorial-php-script-de-previsao-do-tempo/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
	</channel>
</rss>

