Resumo
Page 1 of 1
Resumo
l
Professor: Michel Ferreira, Bases de Dados II, [email protected]
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
Server-side Scripting com uso de PHP
l
PHP é uma server-side scripting language (similar a Active Server Pages (ASP)).
l
Quando um servidor web recebe um pedido HTTP como
GET /index.html HTTP/1.0
o conteúdo do ficheiro index.html é retornado ao requisitante.
l
No entanto, quanto o servidor web recebe um pedido HTTP para um ficheiro PHP, for
example:
GET /test.php HTTP/1.0
o servidor interpreta o conteúdo de test.php e envia o resultado para o requisitante.
l
Por exemplo, se test.php contiver:
<html>
<body>
<?php
print("A classical example: \"Hello, world!\"");
?>
</body>
</html>
o HTML resultante é:
<html>
<body>
A classical example: "Hello, world!"
</body>
</html>
l
Experimente aqui: test.php.
l
Num exemplo mais interessante, se phpinfo.php contiver:
Server-side Scripting com o uso de PHP
<html>
<body>
<?php
phpinfo();
?>
</body>
</html>
o resultado é: phpinfo.php
Page 2 of 2
Contextualizaçao do PHP
Page 1 of 2
Contextualizaçao do PHP
l
l
l
l
PHP foi concebido no Outono de 1994
PHP Versao 4 no segundo trimestre de 2000
PHP é open source, pode obte-la de www.php.net/downloads.php
Equipa de desenvolvimento consiste em mais de 300 pessoas
Estatísticas
Fonte: Netcraft
Janeiro 2002
36,689,008 Domínios consultados
PHP instalado em 25.4% de todos os domínios
Fonte: SecuritySpace.com
Fevereiro 2002
Apache Module Report
1,984,899 Apache Servers observados
846,501 (42.65%) PHP
372,150 (18.75%) Frontpage
319,482 (16.10%) mod_ssl
294,056 (14.81%) OpenSSL
259,995 (13.10%) mod_perl
87,489 (4.41%) ApacheJServ
Plataformas:
l
l
l
l
l
l
l
UNIX (todas as variantes)
Win32 (NT/W95/W98/W2000)
QNX
MacOS (WebTen)
OSX
OS/2
BeOS
Server Interfaces:
Plataformas (experimental):
l
l
OS/390
AS/400
Server Interfaces (Experimental):
Contextualizaçao do PHP
l
l
l
l
l
l
l
l
l
Apache module (UNIX,Win32)
CGI
fhttpd module
ISAPI module (IIS, Zeus)
NSAPI module (Netscape iPlanet)
Java servlet
AOLServer
Roxen module
thttpd module
Page 2 of 2
l
Apache 2.0 module
Porque PHP?
Page 1 of 1
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:
Adabas D InterBase Solid
dBase
mSQL
Sybase
Empress MySQL
Velocis
FilePro Oracle
Unix dbm
Informix PostgreSQL
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
echo("The time and date is now: ");
echo(date("H:i, jS F"));
?>
</body>
</html>
l
Try it here.
l
Este é um exemplo de uma página dinamica.
Tipos em PHP
Page 1 of 1
Tipos em PHP
l
números (inteiros e de vírgula flutuante)
<?php
$a = 1234;
$a = -123;
$a = 1.234;
?>
l
strings
<?php
$a = "abc";
$a = 'abc';
?>
l
// número decimal
// número negativo
// número em vírgula flutuante
// aspas
// pelica
booleanos (true,false)
Tipagem dinamica
l
l
Nao é necessário declarar tipos
A conversao automática é feita
<?php print
( 5 + "1.5" + "10e2"); ?
>
Output:
1006.5
Operadores
Page 1 of 2
Operadores
Operadores aritméticos
example
$a + $b
$a - $b
$a * $b
$a / $b
$a % $b
name
Addition
Subtraction
Multiplication
Division
Modulus
result
Sum of $a and $b.
$b subtracted from $a.
Product of $a and $b.
Dividend of $a and $b.
Remainder of $a divided by $b.
Operadores de String
Existe apenas um operador de string: o operador de concatenaçao (".").
$a = "Hello ";
$b = $a . "World!"; // now $b = "Hello World!"
No entanto, existem algumas funçoes básicas de strings:
substr
trim
strlen
, etc.
Operadores Lógicos
example
$a and $b
$a or $b
$a xor $b
! $a
$a && $b
$a || $b
name
And
Or
Or
Not
And
Or
result
True of both $a and $b are true.
True if either $a or $b is true.
True if either $a or $b is true, but not both.
True if $a is not true.
True of both $a and $b are true.
True if either $a or $b is true.
Operadores de comparaçao
example name
$a == $b Equal
$a != $b Not equal
result
True if $a is equal to $b.
True if $a is not equal to $b.
Operadores
$a < $b
$a > $b
$a <= $b
$a >= $b
Less than
Greater than
Less than or equal to
Greater than or equal to
Page 2 of 2
True if $a is strictly less than $b.
True if $a is strictly greater than $b.
True if $a is less than or equal to $b.
True if $a is greater than or equal to $b.
Sintaxe semelhante ao Java
Sintaxe semelhante ao Java
Todas as estruturas tradicionais de programaçao (Java/C/C++) estao disponiveis:
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.
Page 1 of 1
Vectores
Page 1 of 2
Vectores
Vectores ordenados
<?
$a[0] = 1;
$a[1] = "foo";
$a[2] = array ("Homer", "Marge","Bart",
"Lisa");
?>
Vectores indexados por strings
<?
$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:
You are using Internet Explorer
Funçoes PHP
Page 1 of 2
Funçoes PHP
l
Funçoes built-in: date, phpinfo, substr, etc.
l
As funçoes sao úteis para estruturar o código:
<html>
<body>
<?php
function weekplan($n, $lecture) {
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.
Valores por defeito
Funçoes PHP
<?
function header($title="Default Title" ) {?>
<HTML><HEAD><TITLE>
<? echo $title ?>
</TITLE></HEAD><BODY> <?
}
?>
Page 2 of 2
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
function weekplan($n, $lecture) {
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>
l
Experimente aqui com N=5.
Argumentos
l
Experimente aqui com N=13.
Page 2 of 2
Visibilidade de variáveis em PHP
Page 1 of 1
Visibilidade de variáveis em PHP
l
As variáveis tem visibilidade local. Para referenciar uma variável com visibilidade global usase o comando
global
l
variável
Aviso: As regras de visibilidade causam muitos problemas. Considere:
<html>
<body>
<?php
$a = 1; /* global scope */
function test () {
global $a;
print( "a = $a <br>" ); /* reference to local scope variable *
$a++;
}
test ();
print( "a = $a" ); /* reference to global scope variable */
?>
</body>
</html>
l
Experimente com declaraçao global.
l
Experimente sem declaraçao global.
Variáveis PHP em formulários HTML
Page 1 of 2
Variáveis PHP em formulários HTML
l
As variáveis num script PHP podem obter o seu valor de um formulário HTML (note o uso da
variável PHP_SELF ):
<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.
l
Podemos sempre inicializar a variável por test.php?name=Disco Stu .
Guardando o estado
Um "truque" comum é passar a variável nos links gerados:
...
<a href="edit_person_info.php?pid=27">Henrik Hulgaard</a>
...
No script edit_person_info.php , existirá tipicamente um formulário com informaçao acerca da
pessoa com id 27. Quando o formulário é submitido, o script de update precisa de saber o id. Isto é
feito guardando o id num campo escondido no formulário:
Variáveis PHP em formulários HTML
...
<input type=hidden name=pid value=<? echo $pid ?>>
...
Page 2 of 2
Leitura de ficheiros
Page 1 of 2
Leitura de ficheiros
l
Para abrir um ficheiro usa-se fopen, e fecha-se com fclose .
l
Exemplo. Considere o código:
<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>
l
Leitura do ficheiro lectures.txt:
Introduction,JavaScript,PHP,MySQL
l
Experimente aqui
Leitura de um URL
<? $file = fopen
("http://www.php.net/file.txt" , "r"); ?>
Escrita para um ficheiro
Leitura de ficheiros
<?
$file = fopen("agent.log" , "a");
fputs($file, $HTTP_USER_AGENT ."\n");
?>
Page 2 of 2
Include
Page 1 of 1
Include
l
O comando include pode ser usado para incluir um ficheiro php noutro.
l
Exemplo: Suponha que o ficheiro StandardFunctions.php contém um conjunto de funçoes
usadas em muitas páginas. Cada uma destas páginas deve entao começar com o comando:
<?php
include 'StandardFunctions.php';
?>
Uma aplicaçao simples de Album Fotográfico
Page 1 of 1
Uma aplicaçao simples de Album Fotográfico
<h1>Welcome to my Photo Album</h1>
<?
$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);
?>
O resultado é este: Photo Album Example
Suporte para File Upload
Suporte para File Upload
<h1>Welcome to my Photo Album</h1>
<form action=" <?echo $PHP_SELF?> " enctype="multipart/form data" method=POST>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input type=file name=file size=29>
<input type="submit" value=" Send File ">
</form>
<?
if($file) {
$formats = array('jpg','gif','png');
$dest = "images/$file_name" ;
if(in_array(strtolower(substr($file_name ,-3)),$formats)) {
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);
?>
O resultado é este: Photo Album Example
Page 1 of 1
Debugging
Page 1 of 1
Debugging
l
Para terminar a execuçao de um programa usa-se exit;
l
Alternativamente, para relatar um erro e parar:
die( "Could not execute query" );
Isto é útil para
...
if(!do_something( ... )) die( "Failed doing something" );
...
Extensoes
Page 1 of 1
Extensoes
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
GD (GIF, JPEG, PNG, WBMP)
LDAP
SNMP
IMAP (POP, NNTP)
FTP
MCAL
IMSP
IPTC
BC/GMP (arbitrary precision math)
Hyperwave
XML parser
PDF generation
FDF (PDF forms)
System V Semaphores and Shared
memory
DCOM (Win32 only)
Java Connectivity
mnogosearch (udmsearch support)
Cybermut
Iconv
Satellite
Curl
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
l
gettext (GNU internationalization)
zlib (compressed IO)
Charset/text conversion (UTF-8, Cyrillic,
Hebrew)
Browser capabilities extension
EXIF
SWF (Flash)
ASPELL/PSPELL
MCRYPT
Cybercash
Recode
Readline
XSLT (Sablotron, libxslt, Xalan)
WDDX
NIS
YAZ (Z39.50 client)
Payflow Pro
CCVS (Credit Card Verification System)
Fribidi
Ncurses
Muscat
Recursos
Page 1 of 1
Recursos
Literatura relevante
l
l
L. Welling, L. Thompson: PHP and MySQL Web Development, Sams, 2001
J. Castagnetto, et al: Professional PHP Programming, Wrox, 2000
On-line
PHP Home Page: http://www.php.net
PHP Manual: http://www.php.net/manual/
Tutorial: http://www.php.net/tut.php
Books: http://www.php.net/books.php
Download

PHP Slides