Upload
hoangminh
View
216
Download
0
Embed Size (px)
Citation preview
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
Page 1 of 1Resumo
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:
o HTML resultante é:
l Experimente aqui: test.php.
l Num exemplo mais interessante, se phpinfo.php contiver:
<html> <body> <?php print("A classical example: \"Hello, world!\""); ?> </body> </html>
<html> <body> A classical example: "Hello, world!" </body> </html>
Page 1 of 2Server-side Scripting com o uso de PHP
o resultado é: phpinfo.php
<html> <body> <?php phpinfo(); ?> </body> </html>
Page 2 of 2Server-side Scripting com o uso de PHP
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 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 UNIX (todas as variantes) l Win32 (NT/W95/W98/W2000) l QNX l MacOS (WebTen) l OSX l OS/2 l BeOS
Plataformas (experimental):
l OS/390 l AS/400
Server Interfaces: Server Interfaces (Experimental):
Page 1 of 2Contextualizaçao do PHP
l Apache module (UNIX,Win32) 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
l Apache 2.0 module
Page 2 of 2Contextualizaçao do PHP
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.
Adabas D InterBase SoliddBase mSQL SybaseEmpress MySQL VelocisFilePro Oracle Unix dbmInformix PostgreSQL
Page 1 of 1Porque PHP?
Conceitos básicos l Agora podemos começar a programar o conteúdo de uma página web:
l Try it here.
l Este é um exemplo de uma página dinamica.
<html> <body> <?php echo("The time and date is now: "); echo(date("H:i, jS F")); ?> </body> </html>
Page 1 of 1Conceitos básicos
Tipos em PHP l números (inteiros e de vírgula flutuante)
l strings
l booleanos (true,false)
Tipagem dinamica
l Nao é necessário declarar tipos l A conversao automática é feita
Output:
<?php $a = 1234; // número decimal $a = -123; // número negativo $a = 1.234; // número em vírgula flutuante ?>
<?php $a = "abc"; // aspas $a = 'abc'; // pelica ?>
<?php print( 5 + "1.5" + "10e2"); ?>
1006.5
Page 1 of 1Tipos em PHP
Operadores Operadores aritméticos
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
Operadores de comparaçao
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.
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.
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.
Page 1 of 2Operadores
$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.
Page 2 of 2Operadores
Sintaxe semelhante ao Java Todas as estruturas tradicionais de programaçao (Java/C/C++) estao disponiveis:
l Experimente aqui.
if-then-else-constructsfor-loopswhile-loopsswitch-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>
Page 1 of 1Sintaxe semelhante ao Java
Vectores Vectores ordenados
Vectores indexados por strings
l Exemplo de vectores:
l Experimente aqui.
<? $a[0] = 1; $a[1] = "foo"; $a[2] = array ("Homer", "Marge","Bart", "Lisa"); ?>
<? $catch_it['cat'] = "mouse"; $catch_it['dog'] = "cat"; ?>
<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>
Page 1 of 2Vectores
Page 2 of 2Vectores
Mudança de modo
Output:
<? if(strstr($HTTP_USER_AGENT,"MSIE")) { ?> <b>You are using Internet Explorer</b> <? } else { ?> <b>You are not using Internet Explorer</b> <? } ?>
You are using Internet Explorer
Page 1 of 1Mudança de modo
Funçoes PHP l Funçoes built-in: date, phpinfo, substr, etc.
l As funçoes sao úteis para estruturar o código:
l Experimente aqui.
Valores por defeito
<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>
Page 1 of 2Funçoes PHP
<? function header($title="Default Title") {?> <HTML><HEAD><TITLE> <? echo $title ?> </TITLE></HEAD><BODY> <? } ?>
Page 2 of 2Funçoes PHP
Argumentos l As variáveis em PHP podem ser inicializadas no URL:
localhost/.../test.php?N=5
l Por exemplo:
l Experimente aqui com N=5.
<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>
Page 1 of 2Argumentos
l Experimente aqui com N=13.
Page 2 of 2Argumentos
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:
l Experimente com declaraçao global.
l Experimente sem declaraçao global.
<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>
Page 1 of 1Visibilidade de variáveis em PHP
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):
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:
<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>
Page 1 of 2Variáveis PHP em formulários HTML
... <input type=hidden name=pid value=<? echo $pid ?>> ...
Page 2 of 2Variáveis PHP em formulários HTML
Leitura de ficheiros l Para abrir um ficheiro usa-se fopen, e fecha-se com fclose .
l Exemplo. Considere o código:
l Leitura do ficheiro lectures.txt:
l Experimente aqui
Leitura de um URL
Escrita para um ficheiro
<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
<? $file = fopen("http://www.php.net/file.txt" , "r"); ?>
Page 1 of 2Leitura de ficheiros
<? $file = fopen("agent.log", "a"); fputs($file, $HTTP_USER_AGENT."\n"); ?>
Page 2 of 2Leitura de ficheiros
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'; ?>
Page 1 of 1Include
Uma aplicaçao simples de Album Fotográfico
O resultado é este: Photo Album Example
<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); ?>
Page 1 of 1Uma aplicaçao simples de Album Fotográfico
Suporte para File Upload
O resultado é este: Photo Album Example
<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); ?>
Page 1 of 1Suporte para File Upload
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" ); ...
Page 1 of 1Debugging
Extensoes
l GD (GIF, JPEG, PNG, WBMP) l LDAP l SNMP l IMAP (POP, NNTP) l FTP l MCAL l IMSP l IPTC l BC/GMP (arbitrary precision math) l Hyperwave l XML parser l PDF generation l FDF (PDF forms) l System V Semaphores and Shared
memory l DCOM (Win32 only) l Java Connectivity l mnogosearch (udmsearch support) l Cybermut l Iconv l Satellite l Curl
l gettext (GNU internationalization) l zlib (compressed IO) l Charset/text conversion (UTF-8, Cyrillic,
Hebrew) l Browser capabilities extension l EXIF l SWF (Flash) l ASPELL/PSPELL l MCRYPT l Cybercash l Recode l Readline l XSLT (Sablotron, libxslt, Xalan) l WDDX l NIS l YAZ (Z39.50 client) l Payflow Pro l CCVS (Credit Card Verification System) l Fribidi l Ncurses l Muscat
Page 1 of 1Extensoes
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.netPHP Manual: http://www.php.net/manual/
Tutorial: http://www.php.net/tut.phpBooks: http://www.php.net/books.php
Page 1 of 1Recursos