Escolar Documentos
Profissional Documentos
Cultura Documentos
PHPSlides PDF
PHPSlides PDF
Resumo
l Professor: Michel Ferreira, Bases de Dados II, michel@ncc.up.pt
l Resumo:
1. Contexto e motivaçao para PHP
2. Apresentaçao de PHP
n Conceitos básicos - Tipos, Sintaxe, Operadores, ...
n Funçoes, Argumentos, Visibilidade
3. Manipulaçao de ficheiros
4. Exemplo
n Album de fotografias
n Suporte de File Upload
5. Debugging
6. Extensoes
7. Recursos
8. Como fazer
n Em casa
n No DCC
Server-side Scripting com o uso de PHP Page 1 of 2
l No entanto, quanto o servidor web recebe um pedido HTTP para um ficheiro PHP, for
example:
<html>
<body>
<?php
print("A classical example: \"Hello, world!\"");
?>
</body>
</html>
o HTML resultante é:
<html>
<body>
A classical example: "Hello, world!"
</body>
</html>
<html>
<body>
<?php
phpinfo();
?>
</body>
</html>
o resultado é: phpinfo.php
Contextualizaçao do PHP Page 1 of 2
Contextualizaçao do PHP
l PHP foi concebido no Outono de 1994
l PHP Versao 4 no segundo trimestre de 2000
l PHP é open source, pode obte-la de www.php.net/downloads.php
l Equipa de desenvolvimento consiste em mais de 300 pessoas
Estatísticas
Porque PHP?
l Open Source
l Simples
l O aspecto mais forte e significativo no PHP é o seu suporte para um vasto conjunto de
sistemas de base de dados. Escrever aplicaçoes web suportadas por bases de dados é
excepcionalmente simples em PHP. As seguintes bases de dados sao actualmente suportadas:
l PHP também inclui suporte para falar com outros serviços usando protocolos como IMAP,
SNMP, NNTP, POP3, ou mesmo HTTP. É também possível abrir raw network sockets e
interagir usando outros protocolos.
l É fácil transferir o conhecimento de PHP para outra serverside scripting language tal como
ASP.
Conceitos básicos Page 1 of 1
Conceitos básicos
l Agora podemos começar a programar o conteúdo de uma página web:
<html>
<body>
<?php
?>
</body>
</html>
l Try it here.
Tipos em PHP
l números (inteiros e de vírgula flutuante)
<?php
$a = 1234; // número decimal
$a = -123; // número negativo
$a = 1.234; // número em vírgula flutuante
?>
l strings
<?php
$a = "abc"; // aspas
$a = 'abc'; // pelica
?>
l booleanos (true,false)
Tipagem dinamica
<?php print
( 5 + "1.5" + "10e2"); ?
>
Output:
1006.5
Operadores Page 1 of 2
Operadores
Operadores aritméticos
Operadores de String
$a = "Hello ";
$b = $a . "World!"; // now $b = "Hello World!"
substr
trim
strlen
, etc.
Operadores Lógicos
Operadores de comparaçao
if-then-else -constructs
for-loops
while -loops
switch -constructs
<html>
<body>
<h2>Weekplan </h2>
<table border=1>
<tr>
<th>Week</th><th>Lecture</th>
</tr>
<?php
$lecture = "XML";
for($week=1;$week<13;$week++) {
print("<tr><th>".$week."</th>");
print("<th>".$lecture."</th></tr>\n");
$lecture = "X".$lecture;
};
?>
</table>
</body>
</html>
l Experimente aqui.
Vectores Page 1 of 2
Vectores
Vectores ordenados
<?
$a[0] = 1;
$a[1] = "foo";
$a[2] = array ("Homer", "Marge","Bart",
"Lisa");
?>
<?
$catch_it['cat'] = "mouse";
$catch_it['dog'] = "cat";
?>
l Exemplo de vectores:
<html>
<body>
<h2>Weekplan</h2>
<table border=1>
<tr>
<th>Week</th><th>Lecture</th>
</tr>
<?php
$lecture = array("Introduction","JavaScript","PHP","MySQL");
for($week=1;$week<5;$week++) {
print("<tr><th>".$week."</th>");
print("<th>".$lecture[$week -1]."</th></tr>\n");
};
?>
</table>
</body>
</html>
l Experimente aqui.
Vectores Page 2 of 2
Mudança de modo Page 1 of 1
Mudança de modo
<? if(strstr($HTTP_USER_AGENT ,"MSIE")) { ?>
<b>You are using Internet Explorer</b>
<? } else { ?>
<b>You are not using Internet Explorer</b>
<? } ?>
Output:
Funçoes PHP
l Funçoes built-in: date, phpinfo, substr, etc.
<html>
<body>
<?php
echo("<h2>Weekplan</h2>");
echo("<table border=1>");
echo("<tr>");
echo("<th>Week</th><th>Lecture</th>");
echo("</tr>");
$week=1;
while($week<=$n) {
echo("<tr><th>".$week."</th>");
echo("<th>".$lecture."</th></tr>\n");
$lecture = "X".$lecture;
$week++;
};
};
weekplan(6,"ML");
?>
</table>
</body>
</html>
l Experimente aqui.
<?
function header($title="Default Title" ) {?>
<HTML><HEAD><TITLE>
<? echo $title ?>
</TITLE></HEAD><BODY> <?
}
?>
Argumentos Page 1 of 2
Argumentos
l As variáveis em PHP podem ser inicializadas no URL:
localhost/.../test.php?N=5
l Por exemplo:
<html>
<body>
<?php
echo("<h2>Weekplan</h2>");
echo("<table border=1>");
echo("<tr>");
echo("<th>Week</th><th>Lecture</th>");
echo("</tr>");
$week=1;
while($week<=$n) {
echo("<tr><th>".$week."</th>");
echo("<th>".$lecture."</th></tr>\n");
$lecture = "X".$lecture;
$week++;
};
};
weekplan($N,"ML");
?>
</table>
</body>
</html>
global variável
<html>
<body>
<?php
$a = 1; /* global scope */
function test () {
global $a;
print( "a = $a <br>" ); /* reference to local scope variable *
$a++;
}
test ();
?>
</body>
</html>
<html>
<body>
<?php
if ( $name ) {
print( "Hello $name !" );
} else {
// Form entry:
print( "<form action=\"$PHP_SELF\" method=post>\n" );
print( "Your Name: <input type=text size=10 name=name ><br>\n"
print( "<input type=submit value=Submit>\n" );
print( "</form>\n" );
}
?>
</body>
</html>
l Experimente aqui.
Guardando o estado
...
<a href="edit_person_info.php?pid=27">Henrik Hulgaard</a>
...
...
<input type=hidden name=pid value=<? echo $pid ?>>
...
Leitura de ficheiros Page 1 of 2
Leitura de ficheiros
l Para abrir um ficheiro usa-se fopen, e fecha-se com fclose .
<html>
<body>
<h2>Weekplan</h2>
<table border=1>
<tr>
<th>Week</th><th>Lecture</th>
</tr>
<?php
$fp = fopen("lectures.txt","r");
$week = 1;
$filestring = fgets($fp,100);
$lectures = explode(",",$filestring);
while($lectures[$week -1]) {
print("<tr><th>".$week."</th>");
print("<th>".$lectures[$week -1]."</th></tr>\n");
$week++;
};
fclose($fp);
?>
</table>
</body>
</html>
Introduction,JavaScript,PHP,MySQL
l Experimente aqui
Leitura de um URL
<?
$file = fopen("agent.log" , "a");
fputs($file, $HTTP_USER_AGENT ."\n");
?>
Include Page 1 of 1
Include
l O comando include pode ser usado para incluir um ficheiro php noutro.
<?php
include 'StandardFunctions.php';
?>
Uma aplicaçao simples de Album Fotográfico Page 1 of 1
if(!copy($file,$dest)) {
echo "Unable to create $dest -
check permissions<br> \n";
exit;
}
}
}
$fd = opendir("images");
while($entry = readdir($fd)) {
if(eregi("\.(jpg|gif|png) $",$entry)) {
echo "<a href=\"images/$entry \">";
echo "<img src=\"images/
$entry\" align=middle border=0 height=80 width=100>" ;
echo "</a> $entry<br> \n";
}
}
closedir($fd);
?>
Debugging
l Para terminar a execuçao de um programa usa-se exit;
...
if(!do_something( ... )) die( "Failed doing something" );
...
Extensoes Page 1 of 1
Extensoes
l GD (GIF, JPEG, PNG, WBMP) l gettext (GNU internationalization)
l LDAP l zlib (compressed IO)
l SNMP l Charset/text conversion (UTF-8, Cyrillic,
l IMAP (POP, NNTP) Hebrew)
l FTP l Browser capabilities extension
l MCAL l EXIF
l IMSP l SWF (Flash)
l IPTC l ASPELL/PSPELL
l BC/GMP (arbitrary precision math) l MCRYPT
l Hyperwave l Cybercash
l XML parser l Recode
l PDF generation l Readline
l FDF (PDF forms) l XSLT (Sablotron, libxslt, Xalan)
l System V Semaphores and Shared l WDDX
memory l NIS
l DCOM (Win32 only) l YAZ (Z39.50 client)
l Java Connectivity l Payflow Pro
l mnogosearch (udmsearch support) l CCVS (Credit Card Verification System)
l Cybermut l Fribidi
l Iconv l Ncurses
l Satellite l Muscat
l Curl
Recursos Page 1 of 1
Recursos
Literatura relevante
On-line