Está en la página 1de 29

Resumo

Page 1 of 1

  Resumo l P r o f e s s o r : Michel Ferreira,
  Resumo l P r o f e s s o r : Michel Ferreira,
 

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

n Suporte de File Upload   5. Debugging 6. Extensoes 7. Recursos 8. Como fazer  
n Suporte de File Upload   5. Debugging 6. Extensoes 7. Recursos 8. Como fazer  

Server-side Scripting com o uso de PHP

Page 1 of 2

Server-side Scripting com o uso de PHP Page 1 of 2 Server-side Scripting com uso de

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:

  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

<body> <?php phpinfo(); ?> </body> </html> o resultado é: phpinfo.php

Contextualizaçao do PHP

Page 1 of 2

Contextualizaçao do PHP Page 1 of 2 Contextualizaçao do PHP l PHP foi concebido no Outono

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

consiste em mais de 300 pessoas Estatísticas Fonte: Netcraft 3 6 , 6 8 9 ,

Fonte: Netcraft

36,689,008 Domínios consultados

Janeiro 2002

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:

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

l NSAPI module (Netscape iPlanet) l Java servlet l AOLServer l Roxen module l thttpd module

Porque PHP?

Page 1 of 1

Porque PHP? Page 1 of 1 Porque PHP? l Open Source l Simples l O aspecto

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

Unix dbm

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.

protocolos. l É fácil transferir o conhecimento de PHP para outra serverside scripting language tal como

Conceitos básicos

Page 1 of 1

  Conceitos básicos   l Agora podemos começar a programar o conteúdo de uma página
  Conceitos básicos   l Agora podemos começar a programar o conteúdo de uma página
  Conceitos básicos   l Agora podemos começar a programar o conteúdo de uma página
 

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.

jS F")); ?> </body> </html> l Try it here . l Este é um exemplo de
jS F")); ?> </body> </html> l Try it here . l Este é um exemplo de
jS F")); ?> </body> </html> l Try it here . l Este é um exemplo de

Tipos em PHP

Page 1 of 1

  Tipos em PHP   l números (inteiros e de vírgula flutuante) <?php $a =
  Tipos em PHP   l números (inteiros e de vírgula flutuante) <?php $a =
  Tipos em PHP   l números (inteiros e de vírgula flutuante) <?php $a =
 

Tipos em PHP

 

l

números (inteiros e de vírgula flutuante)

<?php $a = 1234; $a = -123; $a = 1.234;

// número decimal // número negativo // número em vírgula flutuante

 

?>

l

strings

<?php $a = "abc"; $a = 'abc';

// aspas

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

automática é feita <?php print ( 5 + "1.5" + "10e2" ); ?   > Output:
automática é feita <?php print ( 5 + "1.5" + "10e2" ); ?   > Output:
automática é feita <?php print ( 5 + "1.5" + "10e2" ); ?   > Output:

Operadores

Page 1 of 2

Operadores Page 1 of 2 Operadores Operadores aritméticos example name $a + $b Addition $a -

Operadores

Operadores aritméticos

example name $a + $b Addition $a - $b $a * $b $a / $b
example name
$a + $b Addition
$a - $b
$a * $b
$a / $b
$a % $b
Subtraction
result
Sum of $a and $b.
$b subtracted from $a.
Multiplication Product of $a and $b.
Division
Modulus
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 name result $a and $b And True of both $a and $b
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 $a == $b Equal $a != $b Not equal result True if $a
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

Page 2 of 2

$a < $b $a > $b Less than True if $a is strictly less than
$a < $b
$a > $b
Less than
True if $a is strictly less than $b.
Greater than
$a <= $b Less than or equal to
True if $a is strictly greater than $b.
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
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.

$lecture = "X".$lecture; }; ?> </table> </body> </html> l Experimente aqui .
$lecture = "X".$lecture; }; ?> </table> </body> </html> l Experimente aqui .
$lecture = "X".$lecture; }; ?> </table> </body> </html> l Experimente aqui .

Vectores

Page 1 of 2

Vectores Page 1 of 2 Vectores ordenados Vectores <? $a [ 0 ] = 1 ;

Vectores ordenados

Vectores

<? $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","MyS 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

Vectores Page 2 of 2

Mudança de modo

Page 1 of 1

Mudança de modo Page 1 of 1 Mudança de modo <? if( strstr ( $HTTP_USER_AGENT ,

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

<b>You are not using Internet Explorer</b> <? } ?> Output: You are using Internet Explorer

Funçoes PHP

Page 1 of 2

Funçoes PHP Page 1 of 2 Funçoes PHP l Funçoes built-in: date , phpinfo , substr

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

}

?>

<? echo $title ?> </TITLE></HEAD><BODY> <? } ?>

Argumentos

Page 1 of 2

Argumentos Page 1 of 2 Argumentos l As variáveis em PHP podem ser inicializadas no URL:

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.

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 Page 1 of 1 Visibilidade de variáveis em PHP l As

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 va $a++;

}

test ();

print( "a = $a" ); /* reference to global scope variable

?>

</body>

</html>

l

Experimente com declaraçao global.

l

Experimente sem declaraçao global.

</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 Page 1 of 2 Variáveis PHP em formulários HTML l As

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

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 Page 1 of 2 Leitura de ficheiros l Para abrir um ficheiro usa-se

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
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"); ?>

$file = fopen ( "agent.log" , "a" ); fputs ( $file , $HTTP_USER_AGENT . "\n" );

Include

Page 1 of 1

Include Page 1 of 1 Include l O comando include pode ser usado para incluir um

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

?>

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 Page 1 of 1 Uma aplicaçao simples de Album Fotográfico

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

"</a> $entry<br> \n " ; } } closedir ( $fd ); ?> O resultado é este:

Suporte para File Upload

Page 1 of 1

Suporte para File Upload Page 1 of 1 Suporte para File Upload <h1>Welcome to my Photo

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

"</a> $entry<br> \n " ; } } closedir ( $fd ); ?> O resultado é este:

Debugging

Page 1 of 1

  Debugging l Para terminar a execuçao de um programa usa-se exit;   l Alternativamente,
  Debugging l Para terminar a execuçao de um programa usa-se exit;   l Alternativamente,
  Debugging l Para terminar a execuçao de um programa usa-se exit;   l Alternativamente,
 

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" );

"Could not execute query" ); Isto é útil para if(!do_something( )) die( "Failed doing something" );
"Could not execute query" ); Isto é útil para if(!do_something( )) die( "Failed doing something" );
"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
  Extensoes l GD (GIF, JPEG, PNG, WBMP) l gettext (GNU internationalization) l LDAP l
  Extensoes l GD (GIF, JPEG, PNG, WBMP) l gettext (GNU internationalization) l LDAP l
 

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

Card Verification System) l Cybermut l Fribidi l Iconv l Ncurses l Satellite l Muscat l
Card Verification System) l Cybermut l Fribidi l Iconv l Ncurses l Satellite l Muscat l
Card Verification System) l Cybermut l Fribidi l Iconv l Ncurses l Satellite l Muscat l

Recursos

Page 1 of 1

Recursos Page 1 of 1 Recursos Literatura relevante l l L. Welling, L. Thompson: PHP and

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

T u t o r i a l : http://www.php.net/tut.php B o o k s :