Escolar Documentos
Profissional Documentos
Cultura Documentos
Apostila PHP
Apostila PHP
1
APOSTILA DE PHP
2
APOSTILA DE PHP
Apostila de
PHP
3
APOSTILA DE PHP
Aparecido Quesada
Adriana Tosta
Eder Moura Dourado
Simone Leal dos Santos
Thyago Akira de Morais Ribeiro
Yuri Robinson de Souza
Contato
treinamento_cge@prefeitura.sp.gov.br
telecentros@prefeitura.sp.gov.br
PALÁCIO DO ANHANGABAÚ
VIADUTO DO CHÁ Nº 15
CEP 01002-000 SÃO PAULO
TEL: 3113-8938 FAX 3113-8939
4
APOSTILA DE PHP
Índice
5
APOSTILA DE PHP
6
APOSTILA DE PHP
7
APOSTILA DE PHP
8
APOSTILA DE PHP
O que é PHP?
História
9
APOSTILA DE PHP
Vantagens
10
APOSTILA DE PHP
Visualização:
Configuração
PC 386 ou superior
16 MB de memória RAM
100 MB livres em disco (PHP + MySQL + Apache)
11
APOSTILA DE PHP
Software:
Instalação do MySQL
12
APOSTILA DE PHP
#cd /usr/src
13
APOSTILA DE PHP
14
APOSTILA DE PHP
Teste de Funcionamento
Ex:
http://localhost/pastahabilitada/teste.php.
<?php
phpinfo();
?>
15
APOSTILA DE PHP
16
APOSTILA DE PHP
<html>
<head>
<title>Script PHP</title>
</head>
<body>
<?php
echo “Olá, eu sou um script PHP!!!”;
?>
</body>
</html>
COMENTÁRIOS
17
APOSTILA DE PHP
<?
echo teste; /* Isto é um comentário com mais
de uma linha, mas não funciona corretamente ?>
*/
<?
echo teste; /* Isto é um comentário com mais
de uma linha que funciona corretamente
*/
?>
EXERCICÍOS
18
APOSTILA DE PHP
<html>
<title>Exercicio 1</title>
<body>
A primeira linha e <u>normal</u>. <br>
<br>
Nisto, vem uma <font color=#FF0000>terceira mais
complexa</font>... <br>
</body>
</html>
Variáveis
19
APOSTILA DE PHP
INTEGER (INTEIRO)
STRINGS
20
APOSTILA DE PHP
<?
$curso1 = 20;
$curso2 = ‘’curso1 é igual a $curso1'’;
echo $curso2;
// Ficará: $curso2 = ‘’curso1 é igual a 20'’
?>
<?
$curso1 = 20;
$curso2 = ‘curso1 não é igual a $curso1’;
echo $curso2;
// Ficará: $curso2 = ‘’curso1 não é igual a $curso1'’
?>
BOOLEANO
ARRAY
OBJETO
21
APOSTILA DE PHP
Caracteres de Escape
EXERCÍCIOS:
22
APOSTILA DE PHP
<html>
<title>Exercicio 2</title>
<body>
<?
$inteiro=10;
$real=20.0;
$caracter= ‘V’;
$cor1= “#FF0000”;
$cor2= “#0000FF”;
?>
</body>
</html>
23
APOSTILA DE PHP
Operadores
ARITMÉTICOS
OPERADOR SIGNIFICADO
+ Adição
- Subtração
* Multiplicação
/ Divisão
% Resto de divisão
STRING
<?
$x = ‘’Alô ‘’;
$s = $x.’’Mundo’’;
echo($s.’’\n’’); // Imprimirá ‘’Alô Mundo’’ “
?>
24
APOSTILA DE PHP
ATRIBUIÇÃO
OPERADOR SIGNIFICADO
= Atribuição simples.
<?
$curso = 7;
$curso += 2; //($curso fica com o valor 9)
echo $curso;
?>
25
APOSTILA DE PHP
<?
$resto = 11;
$resto %= 2; //($resto fica com o valor 1)
echo $resto;
?>
++ incremento
— decremento
Exemplos:
LÓGICOS
26
APOSTILA DE PHP
or ‘’ou’’ lógico $a or $b
|| ‘’ou’’ lógico $a || $b
COMPARAÇÃO
== igual a
!= diferente de
<> Diferente de
27
APOSTILA DE PHP
Estruturas de Controle
$a = 1;
if ($a == 1)
{
...
...
...
}
<?
$a = 1;
$b = 2;
if ($a > $b)
{
echo ‘’$a > $b’’;
}
else
{
echo ‘’$b > $a’’;
}
?>
28
APOSTILA DE PHP
<?
$a = 1;
$b = 2;
$c = 3;
if ($a > $b)
{
echo “$a e´ maior que $b”;
}
elseif ($a > $c)
{
echo “$a e´ maior que $c”;
}
else
{
echo “$a e´ menor que $b e $c”;
}
?>
29
APOSTILA DE PHP
if ($i == 0)
print i é igual a zero;
elseif ($i == 1)
print i é igual a um;
elseif ($i == 2)
print i é igual a dois;
}
switch ($i) {
case 0:
print i é igual a zero;
break;
case 1:
print i é igual a um;
break;
case 2:
print i é igual a dois;
break;
}
(expressao1)?(expressao2):( expressao3)
30
APOSTILA DE PHP
<?
echo “While”.”<br>”;
$a = 1;
while ($a <= 10)
{
echo “Número: “.$a++.”<br>”;
}
?>
<?
echo “Do...While”.”<br>”;
$c = 0;
do
{
echo “Número: “.++$c. “<br>”;
} while ($c < 10);
?>
31
APOSTILA DE PHP
<?
echo “For...Next”.”<br>”;
for ($a=0; $a<=10; $a++)
{
echo “Número: “.$a.”<br>”;
}
?>
EXERCICÍOS:
<html>
<title>verifica.php</title>
<body>
<?
//Condicao de texto em italico
if ($italico== “on”)
{
$italico_abre= “<i>”;
$italico_fecha= “</i>”;
}
else
{
$italico_abre= “”;
$italico_fecha= “”;
}
32
APOSTILA DE PHP
33
APOSTILA DE PHP
Quebra de Fluxo
<?
$a = 20;
while ($a > 0)
{
if ($a == 5)
{
echo “Número inválido!”;
break;
}
echo “Número “.$a.”<br>”;
$a—;
}
?>
<?
for ($a=0;$a<10;$a++)
{
if ($a == 5)
{
continue;
}
else
{
echo “Número: “.$a.”<br>”;
}
}
?>
34
APOSTILA DE PHP
Include
Programa: Teste.php
<?
echo ‘’Teste A’’;
echo ‘’Teste B’’;
include ‘’Externo.php’’;
echo ‘’Teste D’’;
?>
Programa: Externo.php
<?
echo ‘’Teste C’’;
?>
<?
echo ‘’Teste A’’;
echo ‘’Teste B’’;
echo ‘’Teste C’’;
echo ‘’Teste D’’;
?>
35
APOSTILA DE PHP
Funções
Onde:
soma é o nome da função.
$a e $b são argumentos.
$c é o valor retornado.
36
APOSTILA DE PHP
<?
$a=12;
$b=14;
echo ‘Exemplo de uso de funções em PHP’;
soma($a,$b);
function soma($a, $b)
{
$c = $a + $b;
return $c;
}
echo “<br>$a<br>$b”;
?>
<?
echo ‘Exemplo de uso de funções em PHP’;
$nome=’FulAno DOs Santos’;
$nome=strtolower($nome);
echo $nome;
?>
37
APOSTILA DE PHP
Passagem de Argumentos
function arg_ref(&$variável)
{
$variável = ‘’valor’’;
}
function mais5($numero) {
$numero += 5;
}
$a = 3;
mais5($a); //$a continua valendo 3
38
APOSTILA DE PHP
39
APOSTILA DE PHP
40
APOSTILA DE PHP
VARIÁVEIS GLOBAIS
Exemplo:
$curso = ‘’PHP’’
function mostra()
{
global $curso;
echo $curso;
}
mostra();
VARIÁVEIS LOCAIS
Exemplo:
function mostra()
{
$x = 15;
echo $x;
}
echo $x; //Não imprimirá nada já que $x não é global
mostra(); //Imprimirá 15
41
APOSTILA DE PHP
VARIÁVEIS ESTÁTICAS
function incrementa()
{
static $x = 0;
echo $x;
$x++;
}
EXERCICÍOS:
<html>
<title>Exercicio</title>
<body>
<?
// calcula a soma de duas variaveis
function soma($a,$b)
{
42
APOSTILA DE PHP
$total=$a+$b;
return ($total);
}
//calcula a subtracao de duas variaveis
function subtracao($a,$b)
{
$total=$a-$b;
return ($total);
}
//calcula a multiplicacao de duas variaveis
function multiplicacao($a,$b)
{
$total=$a*$b;
return ($total);
}
//calcula a divisao de duas variaveis
function divisao($a,$b)
{
$total=$a/$b;
return ($total);
}
43
APOSTILA DE PHP
$div=divisao($a,$b);
echo “A divisão de $a por $b é $div !<br>”;
?>
</body>
</html>
Arrays
<?
$array[0] = “Curso”;
$array[1] = “PHP”;
$array[“MPB”] = “Gilberto Gil”;
echo $array[0].”<br>”;
echo $array[1].”<br>”;
echo $array[“MPB”].”<br>”;
?>
Listas
<?
list($a, $b, $c) = array(0 => ‘’a’’, 1 => ‘’b’’, 2 => ‘’c’’);
?>
44
APOSTILA DE PHP
EXERCICÍOS:
<html>
<title>Exercicio</title>
<body>
<?
$meses=array( “Janeiro”, “Fevereiro”, “Março”, “Abril”,
“Maio”, “Junho”, “Julho”, “Agosto”, “Setembro”, “Outubro”,
“Novembro”, “Dezembro”);
?>
Ciclo While
<br><br>
<?
$mes=0;
while ($mes<=11)
{
echo “Mês: $meses[$mes] <br>”;
$mes++ ;
}
?>
<br><br><br>
Ciclo For
<br><br>
<?
45
APOSTILA DE PHP
46
APOSTILA DE PHP
REALIZANDO CONSULTAS
47
APOSTILA DE PHP
APAGANDO O RESULTADO
NÚMERO DE LINHAS
UTILIZANDO OS RESULTADOS
48
APOSTILA DE PHP
Projeto
Roteiro:
49
APOSTILA DE PHP
Tipos de Campos
50
APOSTILA DE PHP
Dicas:
OPERAÇÃO COMANDO
51
APOSTILA DE PHP
Roteiro:
52
APOSTILA DE PHP
3 - MÓDULO DE INCLUSÃO
53
APOSTILA DE PHP
Dica:
Quando o servidor recebe a requisição de uma página HTML,
ele apenas envia a página requisitada. Por outro lado, quando a
requisição é de uma página com extensão PHP, o servidor processa
o código antes de enviá-la. Pode-se combinar os códigos HTML e
PHP.
54
APOSTILA DE PHP
Dicas:
No código referente ao programa “inclusão.php”, você utilizará
algumas funções do PHP:
<html>
<head>
<title>Inclusao.php</title>
</head>
<body bgcolor=”#FFFFFF”>
<?php
// Consiste Nome
if (empty($nome) || empty($telefone) || empty($cargo))
{
55
APOSTILA DE PHP
56
APOSTILA DE PHP
</form>
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
“);
}
else {
// Declaração SQL
$declar = “INSERT into alunos values (‘$nome’,
$cargo’,
‘$telefone’, ‘$email’)”;
// Roda a query e trata o resultado
57
APOSTILA DE PHP
}
else {
echo (“<BR><BR>”);
echo (“<center> <b> <font size = 4> Erro - Inclusã
o não Efetuada
</font>
</b> </center>”);
echo (“<BR>”);
echo (“<center> <b> <a href=\”inclusao.html\”>
Voltar</a> </b>
</center>”);
}
Roteiro:
58
APOSTILA DE PHP
8.Insira 3 funcionários.
4 - MÓDULO DE CONSULTA
<html>
<head> <title>Consulta.html</title>
</head>
<body bgcolor=”#FFFFFF”>
<table width=”640" border=”0" cellspacing=”0" align=
”center”>
<tr valign=”top”>
<td>
<p><img src=”telecentro.gif” width=”640"
height=”44"></p>
59
APOSTILA DE PHP
<!mensagem>
<p><b>Formulário de Consulta<br>
</b></p>
<form method=”post” action=”consulta.php”>
<p>Nome completo:
<input type=”text” name=”nome” size=”25"
maxlength=”50">
</p>
<p>
<input type=”submit” name=”Submit” value=
”Enviar”> </p>
</form>
<center> <b> <a href=”index.html”>Home</a> </b>
</center>
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</body>
</html>
60
APOSTILA DE PHP
Dicas:
61
APOSTILA DE PHP
<html>
<head>
<title>Consulta.php</title>
</head>
<body bgcolor=”#FFFFFF”>
<?php
// Tira os espaços em branco das variáveis recebidas pelo
formulário
$nome = trim($nome);
// Consiste Nome
if (empty($nome)) {
$html = file(“consulta.html”);
$html = implode(“ “,$html);
$erro = “<center><font color=\”#FF0000\”> Preencha o
campo<b>Nome</b></font></center>”;
$html = str_replace(“<!mensagem>”,$erro,$html);
echo ($html);
}
else {
echo (“<p><center><img src=\”telecentro.gif\” width=\”640\”
height=\”44\”></center></p>”);
// Declaração do SQL
$declar = “SELECT cargo, telefone, email from alunos
where nome = ‘$nome’”;
// Roda a query e verifica se encontrou registro
$query = mysql_db_query (‘telecentros’, $declar, $conec)
or die (“Erro no
acesso ao banco”);
$achou = mysql_num_rows($query);
62
APOSTILA DE PHP
// echo ($achou);
// Se encontrou, guarda as variáveis
if ($achou > 0) {
$row = mysql_fetch_row ($query);
$cargo = $row[0];
$telefone = $row[1];
$email = $row[2];
echo (“<BR>”);
echo (“<table width=\”640\” border=\”0\” cellspacing=\”0\”
align=\”center\”> <tr> <td>”);
echo (“<b> Resultado da Consulta </b>”);
echo (“<BR><BR>”);
echo (“<b> Nome: </b> $nome <BR>”);
echo (“<b> Cargo: </b> $cargo <BR>”);
echo (“<b> Telefone: </b> $telefone <BR>”);
echo (“<b> E-mail: </b> $email <BR>”);
echo (“</td> </tr> </table>”);
echo (“<center> <b> <a href=\”consulta.html\”>Voltar</
a> </b>
</center>”);
}
else {
echo (“<BR>”);
echo (“<center> <b> Aluno não cadastrado
</b> </center>”);
echo (“<BR>”);
echo (“<center> <b> <a href=\”consulta.html\”>Voltar</
a> </b>
</center>”);
}
}
?>
</body>
</html>
63
APOSTILA DE PHP
Roteiro:
64
APOSTILA DE PHP
5 - MÓDULO DE EXCLUSÃO
<html>
<head>
<title>Exclusao.html</title>
<meta http-equiv=”Content-Type” content=”text/
html; charset=iso-8859-1">
</head>
<body bgcolor=”#FFFFFF”>
<table width=”640" border=”0" cellspacing=”0" align=
”center”>
<tr valign=”top”>
<td>
<p><img src=”telecentro.gif” width=
”640" height=”44"></p>
<!mensagem>
<p><b>Formulário de Exclusão: <br>
</b></p>
<form method=”post” action=”exclusao.php”>
<p>Nome Completo:
<input type=”text” name=”nome” size=
”25" maxlength=”50">
</p>
<p>
<input type=”submit” name=”Submit” value=
”Enviar”>
</p>
</form>
<center> <b> <a href=”index.html”>Home</a> </b>
</center>
</td>
</tr>
65
APOSTILA DE PHP
<tr>
<td> </td>
</tr>
</table>
</body>
</html>
<html>
<head>
<title>Exclusao.php</title>
</head>
<body bgcolor=”#FFFFFF”>
<?php
// Consiste Nome
if (empty($nome)) {
$html = file(“exclusao.html”);
$html = implode(“ “,$html);
$erro = “<center><font color=\”#FF0000\”> Preencha o
66
APOSTILA DE PHP
campo<b>Nome</b></font></center>”;
$html = str_replace(“<!mensagem>”,$erro,$html);
echo ($html);
}
else {
echo (“<p><center><img src=\”telecentro.gif\” width=\”640\”
height=\”44\”></center></p>”);
// Declaração do SQL
$declar = “SELECT nome from alunos where nome =
‘$nome’”;
echo (“<BR><BR>”);
echo (“<center> Aluno: $nome </center>”);
echo (“<BR>”);
67
APOSTILA DE PHP
echo (“<BR><BR>”);
echo (“<center> <b> <font size = 4>
Exclusão Efetuada </font> </b>
</center>”);
echo (“<BR><BR>”);
echo (“<center> <b> <a href=\”exclusao.html\”>Voltar</a>
</b>
</center>”);
}
else {
echo (“<BR><BR>”);
echo (“<center> <b> <font size = 4>
Erro - Exclusão não Efetuada
</font>
</b> </center>”);
echo (“<BR><BR>”);
echo (“<center> <b> <a href=\”exclusao.html\”>
Voltar</a> </b>
</center>”);
}
}
else {
echo (“<BR><BR>”);
echo (“<center> <b> Aluno não cadastrado
</b>
</center>”);
echo (“<BR><BR>”);
echo (“<center> <b> <a href=\”exclusao.html\”>Voltar
</a> </b>
</center>”);
}
mysql_close ($conec);
}
?>
</body>
</html>
68
APOSTILA DE PHP
Roteiro:
6 - MÓDULO DE ALTERAÇÃO
69
APOSTILA DE PHP
<html>
<head>
<title>Alteracao.php</title>
</head>
<body bgcolor=”#FFFFFF”>
<?php
include (“funcoes.php”);
// Consiste Nome
if (empty($nome)) {
$html = file(“alteracao.html”);
$html = implode(“ “,$html);
$erro = “<center><font color=\”#FF0000\”> Preencha o
campo<b>Nome</b></font></center>”;
$html = str_replace(“<!mensagem>”,$erro,$html);
echo ($html);
}
else {
echo (“<p><center><img src=\”telecentro.gif\” width=
\”640\”height=\”44\”></center></p>”);
70
APOSTILA DE PHP
// Declaração do SQL
$declar = “SELECT cargo, telefone, email from alunos
where nome = ‘$nome’”;
71
APOSTILA DE PHP
</body>
</html>
72
APOSTILA DE PHP
<?php
function
monta_pagina($nome,$cargo,$telefone,$email)
{
echo “<table width=\”640\” border=\”0\” cellspacing=\”0\”
align=\”center\”>”;
echo “<tr>”;
echo “<td>”;
echo “<p><b>Formulário de Alteraçã
o: <br></b></p>”;
echo “<form method=\”post\” action=\”alteracao2.php\”>”;
echo “<p>Nome: $nome </p>”;
echo “<p>Cargo: <input type=\”text\” name=\”cargo
\” value=\”$cargo\”
size=\”40\” maxlength=\”40\”> </p>”;
echo “<p>Telefone: <input type=\”text\” name=\”telefone\”
value=\”$telefone\” maxlength=\”10\” size=\”10\”> </p>”;
echo “<p>E-mail: <input type=\”text\” name=\”email
\” value=\”$email\”
size=\”25\” maxlength=\”25\”> </p>”;
echo “<p> <input type=\”submit\” name=\”Submit
\” value=\”Enviar\”>
</p>”;
echo “<p> <input type=\”hidden\” name=\”nome
\” value=\”$nome\”></p>”;
echo “</form>”;
echo “</td>”;
echo “</tr>”;
echo “<tr>”;
echo “</tr>”;
echo “</table>”;
echo (“<center> <b> <a href=\”alteracao.html\”>Voltar</a>
</b>
</center>”);
return; }
?>
73
APOSTILA DE PHP
<html>
<head>
<title>Alteracao2.php</title>
<meta http-equiv=”Content-Type” content=”text/
html; charset=iso-8859-1">
</head>
<body bgcolor=”#FFFFFF”>
<p><center><img src=”telecentro.gif” width=
”640" height=”44"></center></p>
<?php
include (“funcoes.php”);
// Tira os espaços em branco das variáveis recebidas
pelo formulário
$nome = trim($nome);
$cargo = trim($cargo);
$telefone = trim($telefone);
$email = trim($email);
74
APOSTILA DE PHP
{
echo (“<font color=\”#FF0000\”>
<b>Campo(s) obrigatório(s) não preenchido(s)
</b></font>”);
monta_pagina($nome, $cargo, $telefone, $email);
}
else
{
// Cria uma conexão com o servidor MySQL
$conec = mysql_connect (“localhost”,”root”,”telecentros”)
or die
// consulta SQL pra atualizar a tabela do banco de dados
$declar=”UPDATE alunos SET nome=
’$nome’, cargo=’$cargo’, email=’$email’, telefone=
’$telefone’ WHERE nome=’$nome’”;
// Roda a query e trata o resultado
if (mysql_db_query (“telecentros”, $declar, $conec)) {
echo (“<BR><BR>”);
echo “<center> <b> <font size = 4> Altera&ção Efetuada!
</font> </b>
</center>”;
echo (“<br>”);
75
APOSTILA DE PHP
Roteiro:
76
APOSTILA DE PHP
para criar uma página simples que agradece ao usuário pelo uso
do sistema, e salve-a com o nome de sair.html.
Dicas:
j: dia
m: mês
Y: ano
H: hora
i: minutos
s: segundos
<html>
<head>
<title>Função Data e Hora</title>
</head>
<body bgcolor=”#FFFFFF”>
<?php
$data = date(“j/m/Y”);
$hora = date(“H:i:s”);
77
APOSTILA DE PHP
$data = date(“Y/m/j”);
• htmlspecialchars
• htmlentities
º para ‘º’
ª para ‘ª’
á para ‘á’
ç para ‘ç’
78
APOSTILA DE PHP
• nl2br
Imprime:
Maurício<br>Vivas<br>
• get_meta_tags
Exemplo:
No arquivo teste.html temos:
...
<head>
<meta name=”author” content=”jose”>
<meta name=”tags” content=”php3 documentation”>
...
</head><!— busca encerra aqui —>
...
a execução da função:
get_meta_tags(“teste.html”);
Devolve o array:
array(“author”=>”jose”,”tags”=>”php3 documentation”);
79
APOSTILA DE PHP
• strip_tags
• urlencode
• urldecode
• Implode e join
80
APOSTILA DE PHP
Exemplo:
• split
• explode
81
APOSTILA DE PHP
• similar_text
Exemplo:
• strcasecmp
• strcmp
82
APOSTILA DE PHP
• strstr
• stristr
• strpos
• strrpos
83
APOSTILA DE PHP
• chop
• ltrim
• trim
• strrev
84
APOSTILA DE PHP
• strtolower
• strtoupper
• ucfirst
• ucwords
85
APOSTILA DE PHP
• str_replace
FUNÇÕES DIVERSAS
• chr
• ord
• echo
• strlen
86
APOSTILA DE PHP
Referência/fontes bibliográficas:
www.php.net
www.phpbuilder.com
www.phpwizard.net
87
APOSTILA DE PHP
Anotações
88
APOSTILA DE PHP
Anotações
89
APOSTILA DE PHP
Anotações
90
APOSTILA DE PHP
Anotações
91
APOSTILA DE PHP
Anotações
92
APOSTILA DE PHP
Anotações
93
APOSTILA DE PHP
Anotações
94
APOSTILA DE PHP
Anotações
95
APOSTILA DE PHP
Anotações
96
APOSTILA DE PHP
Anotações
97
APOSTILA DE PHP
Anotações
98
APOSTILA DE PHP
99
APOSTILA DE PHP
100