Você está na página 1de 29

Resumo Page 1 of 1

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

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 Page 2 of 2

<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

Fonte: Netcraft 36,689,008 Domínios consultados


Janeiro 2002 PHP instalado em 25.4% de todos os domínios
1,984,899 Apache Servers observados
846,501 (42.65%) PHP
Fonte: SecuritySpace.com 372,150 (18.75%) Frontpage
Fevereiro 2002 319,482 (16.10%) mod_ssl
Apache Module Report 294,056 (14.81%) OpenSSL
259,995 (13.10%) mod_perl
87,489 (4.41%) ApacheJServ
Plataformas: Plataformas (experimental):

l UNIX (todas as variantes) l OS/390


l Win32 (NT/W95/W98/W2000) l AS/400
l QNX
l MacOS (WebTen)
l OSX
l OS/2
l BeOS
Server Interfaces: Server Interfaces (Experimental):
Contextualizaçao do PHP Page 2 of 2

l Apache module (UNIX,Win32) l Apache 2.0 module


l CGI
l fhttpd module
l ISAPI module (IIS, Zeus)
l NSAPI module (Netscape iPlanet)
l Java servlet
l AOLServer
l Roxen module
l thttpd 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; // 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

l Nao é necessário declarar tipos


l A conversao automática é feita

<?php print
( 5 + "1.5" + "10e2"); ?
>

Output:

1006.5
Operadores Page 1 of 2

Operadores
Operadores aritméticos

example name result


$a + $b Addition Sum of $a and $b.
$a - $b Subtraction $b subtracted from $a.
$a * $b Multiplication Product of $a and $b.
$a / $b Division Dividend of $a and $b.
$a % $b Modulus 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 name result


$a and $b And True of both $a and $b are true.
$a or $b Or True if either $a or $b is true.
$a xor $b Or True if either $a or $b is true, but not both.
! $a Not True if $a is not true.
$a && $b And True of both $a and $b are true.
$a || $b Or True if either $a or $b is true.

Operadores de comparaçao

example name result


$a == $b Equal True if $a is equal to $b.
$a != $b Not equal True if $a is not equal to $b.
Operadores Page 2 of 2

$a < $b Less than True if $a is strictly less than $b.


$a > $b Greater than True if $a is strictly greater than $b.
$a <= $b Less than or equal to True if $a is less than or equal to $b.
$a >= $b Greater than or equal to True if $a is greater than or equal to $b.
Sintaxe semelhante ao Java Page 1 of 1

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.
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 Page 2 of 2

<?
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

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 Page 2 of 2

l Experimente aqui com N=13.


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 usa-
se o comando

global variável

l 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 Page 2 of 2

...
<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 .

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 Page 2 of 2

<?
$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.

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 Page 1 of 1

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


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 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

l L. Welling, L. Thompson: PHP and MySQL Web Development, Sams, 2001


l 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

Você também pode gostar