php

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Favorites, Groups & Events

    php - Presentation Transcript

    1.  
    2. 1- Instal-lació
    3. 1r: Descarregar el Zip del PHP5 http://es2.php.net/get/php-5.0.3-Win32.zip/from/a/mirror 2n: Descomprimir-lo en una carpeta senzilla ex: c:servidor 3r: Configurem el PHP 4 (C:ServidorPHPphp.ini-dist  C:ServidorPHPphp.ini) extension_dir = "C:/Servidor/PHP/extensions/“ … upload_tmp_dir = "C:/Servidor/PHP/uploads/“ … upload_max_filesize = 1M … session.save_path = "C:xampp mp" 1.1 Instal.lar php5 (Windows)
    4. 4rt: Configurem l’Apache ( httpd.conf ) # Example: # LoadModule foo_module modules/mod_foo.so # LoadModule php5_module C:/Servidor/PHP/php5apache2.dll … DirectoryIndex index.html index.htm index.php AddType application/x-httpd-php .php .php3 .php4 .phtml AddType application/x-httpd-php-source .phps 5é: Probem que funcioni. ( …/htdocs/phpinfo.php ) <? phpinfo();?> 1.1 Instal.lar php5 (Windows)
    5. http://localhost/phpinfo.php 1.1 Instal.lar php5 (Windows)
    6. 1r: Descarregar el PHPMyAdmin http://www.phpmyadmin.net/home_page/downloads.php 2n: Descomprimir-lo en una carpeta de htdocs (ex: ../htocs/phpmyadmin/) 3: Configurar-lo ( ../htdocs/phpmyadmin/config.inc.php ) $cfg['PmaAbsoluteUri'] = ‘http://localhost/phpmyadmin/’; $cfg['blowfish_secret'] = ‘web’; $cfg['Servers'][$i]['auth_type'] = 'config'; $cfg['Servers'][$i]['user'] = ‘usuari'; $cfg['Servers'][$i]['password'] = ‘contrasenya'; 1.2 Instal.lar phpmyadmin (Windows)
    7. http://localhost/phpmyadmin 1.2 Instal.lar phpmyadmin (Windows)
    8. 1r: Descarregar el paquet de PHP http://es.php.net/get/php-5.2.6.tar.bz2/from/a/mirror 2n: Moure’l a alguna carpeta de referencia: (ex: /usr/src/webserver/) 3r: Descomprimir el tar.bz2 4rt: Instal·lar el paquet: 5é: Configurar el php 6é: Configurar l’Apache (Igual que en la versió Windows) tar xjvf php-5.0.2.tar.bz2 cd php-5.0.2 ./configure --prefix=/usr/local/webserver/php --with-mysql=/usr/local/webserver/mysql/ --with-apxs=/usr/local/webserver/apache/bin/apxs make && make install cp php.ini-dist /usr/local/lib/php.ini 1.3 Instal.lar php5 (Linux)
    9. 1r- Descarregar el paquet http://www.phpmyadmin.net/home_page/downloads.php 2n) Crear una carpeta al htdocs de l’Apache (ex: ../htdocs/phpmyadmin) 3r) Descomprimir-lo en la carpeta corresponent 4rt) Configurar el PHPMyAdmin (Igual que en la versió Windows) tar xjvf phpMyAdmin-2.6.0-pl2.tar.bz2 /usr/source/web/phpmyadmin 1.4 Instal.lar phpmyadmin (Linux)
    10. (Apache+PHP+MySQL+PHPMyAdmin) Linux: 1r: Descarregar el TAR http ://www.apachefriends.org/en/xampp-linux.html 2n: Instal·lació: 3r: Encendre / aturar tar xvfz xampp-linux-1.6.8a.tar.gz -C /opt / opt/lampp/lampp start /opt/lampp/lampp stop 1.5
    11. Windows: 1r: Descarregar l’EXE http://www.apachefriends.org/en/xampp-windows.html 2n: Instal·lació: ( Executar l’assistent ) 3r: Encendre / aturar (Xampp Control Panel) (Apache+PHP+MySQL+PHPMyAdmin) 1.5
    12. 2- Introducció
    13. Cookies Cache “ CONNECT” www.server.com 80 GET /index.php HTTP/1.0 INTERNET NAVEGADOR SERVIDOR Servidor WEB port 80 PHP /tmp SESIONS DBMS port 3306 htdocs
    14. 2.1 Hello world: xHtml (1/2)
      • Estàndard del fitxer - http://validator.w3.org/
      • <!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.1//EN&quot; &quot;http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd&quot;>
      • Document xhtml i llenguatge natural usat
      • <html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;ca&quot;>
      • <head>
      • <title>Exemple 1: xhtml --> html + xml</title>
      • codificació del fitxer, llenguatge natural usat, comportament cache navegador, resum del fitxer x crawlers,…
      • <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html;charset=iso-8859-1&quot;/>
      • ……
      • </head>
      • <body>
      • identifica zones de codi per aplicar-hi disseny
      • (css) o manipular-lo (javascript)
      • <div id=&quot;main&quot;><p>Hola Món! <br />Hola Univers!</p></div>
      • <div id=&quot;footer&quot;> Arnau Gavaldà i Enric Mas 2008</div>
      • abans de </body> és fica codi per generar estadístiques
      • </body>
      • </html>
      2.1 Hello world: xHtml (2/2)
      • Codi
        • Inici
          • <?php
        • Fi
          • ?>
      • Variables
        • $var
        • Sensibles a majúscules
        • $var != $Var
      • Comentaris
        • // Comentari
        • /*
        • * Comentari llarg
        • */
      • Escriure text
        • echo “text: $var”;
        • printf(“text: %s”,$var);
      <?php require_once ('./header.html'); $text = “Hello world!&quot;; echo &quot;<p>&quot;.$text.&quot;</p>&quot;; require_once ('./footer.html'); ?> 2.2 Hello world: xHtml + php
    15. 2.3 Tipus bàsics
      • Definició
        • Automàtica en temps d’execució
          • Pseudo-variable: $...
      • Escalars
        • boolean
          • $a = TRUE;
          • $b = FALSE;
        • integer
          • $a = 1234; // número decimal
          • $b = -123; // número enter
          • $c = 0123; // número octal (83 decimal)
          • $d = 0x1A; // número hexadecimal (26 decimal)
        • float (double en desús)
          • $a = 1.234; $b = 1.2e3; $c = 7E-10;
        • string
          • echo ‘imprimeixen tot el que hi ha dins‘;
          • echo “processen caràcters especials , ”variables” $a”;
      • Compostes
        • array (matrius)
        • object
          • programació orientada a objectes
      • Especial
        • NULL
      • Funcions de conversió entre tipus
    16. 2.3 Tipus bàsics: Matrius
      • Introducció
        • Clau
        • Valor (associat a la clau)
      • Crear i afegir
        • Funció array
          • $matriu1 = array(5 => 1, 12 => 2);
        • Parèntesis quadrats
          • $matriu2[] = 56;    // Igual que $matriu2[0] = 56;
          • $matriu3[&quot;x&quot;] = 42; // Afegir amb clau “x” i valor 42
      • Consultar
        • Especificar clau i retorna valor
        • $var = $matriu1[5];
      • Imprimir tot el contingut
        • print_r($matriu);
      • Eliminar
        • Element (Clau i valor associat)
          • unset($matriu4[5]); 
          • // Elimina element amb clau 5
        • Matriu
          • unset($matriu4);    
          • // Elimina tota la matriu
    17. 2.4 Variables
      • Bàsiques
        • $var = {valor};
      • Àmbit
        • Context
          • on la variable està definida (funció)
        • Si es vol importar una global usar
          • global $var;
          • $GLOBALS[‘var'];
      • Estàtiques
        • static $var = {valor};
      • Funcions per
        • Saber tipus
          • $tipus = gettype($var);
        • Comprovar el tipus (retornen booleà)
          • is_array($var); is_float($var); is_int($var); is_string($var); …
      • Reservades
        • $GLOBALS — Variables globals
        • $_SERVER — Info del servidor i entorn execució
        • $_GET — Variables HTTP GET
        • $_POST — Variables HTTP POST
        • $_FILES — Variables de Càrrega d’Arxius HTTP
        • $_SESSION — Variables de sessió
        • $_COOKIE — Cookies
        • $_ENV — Variables de entorn
    18. 2.4 Constants
      • Només tipus escalars
        • Boolean
        • Integer
        • Float
        • Strings
      • Exemple
        • <?php define(&quot;CONSTANT&quot;, &quot;Hello world!&quot;);
        • echo CONSTANT; // sortida &quot;Hello world!&quot; echo Constant; // sortida &quot;Constant&quot; + error ?>
    19. 2.5 Operadors bàsics
      • Aritmètics
        • + - * / % ++ --
      • Cadenes
        • “ a”.”b”
      • Comparació
        • < >= <= == !=
      • Lògics
        • AND && OR || !
      • Assignació
        • = += -= *= /= .=
    20. 2.6 Estructures de control bàsiques
      • if ($i == 0) {
      • print &quot;i igual a 0&quot;;
      • } elseif ($i == 1) {
      • print &quot;i igual a 1&quot;;
      • } elseif ($i == 2) {
      • print &quot;i igual a 2&quot;;
      • } else {
      • print &quot;i > 2&quot;;
      • switch ($i) {
      • case 0:
      • print &quot;i igual a 0&quot;;
      • break;
      • case 1:
      • print &quot;i igual a 1&quot;;
      • break;
      • case 2:
      • print &quot;i igual a 2&quot;;
      • break;
      • default :
      • print &quot;i no és 0, 1 o 2&quot;;
      • }
      • $i = 1;
      • while ($i <= 10) {
      • print $i++;
      • }
      • $i = 0;
      • do {
      • print $i;
      • } while ($i>0);
      • for  ($i = 1; $i <= 10; $i++) {      print $i;
      • }
      • foreach ($arr as $value) {
      • echo “valor: $value<br> &quot;;
      • }
    21. 2.7 Funcions
      • Exemple
        • <?php function suma ($a,$b)  {     $c = $a + $b;     return $c; }
        • echo “$a + $b = $c”; ?>
      • Es poden crear funcions dins de funcions
      • NO admet sobrecàrrega d’operadors
        • function suma($a,$b){…}
        • function suma($a,$b,$c){…}  ERROR
    22. 2.8 Excepcions
      • “ Similars” a Java
      • Exemple
        • try {     $error = ‘Sempre salta aquesta excepció';     throw new Exception($error);     // Code following an exception is not executed.     echo ”no s’executa mai”; } catch (Exception $e) {     echo 'Excepció: ’.  $e->getMessage(). &quot; &quot;; }
    23. 2.9 Dates i temps bàsic
      • Funcions
      • string date (format[,timestamp])
          • d – dia del mes (01-31)
          • m – mes (01-12)
          • Y – any en 4 dígits
      • int mktime (hora,min,seg,mes,dia,any,is_dst)
        • Timestamp (UNIX Timestamp)
          • Nombre de segons des de l’1 de gener de 1970 a 0:00:00 GMT
      • bool checkdate
      • ( int $mes , int $dia , int $any )
      • Exemple
      • echo &quot;<p> Avui és &quot;.date(&quot;d/m/Y&quot;).&quot;</p> &quot;;
      • $dema = mktime(0,0,0,date(&quot;m&quot;),
      • date(&quot;d&quot;)+1,date(&quot;Y&quot;));
      • echo &quot;<p> Demà serà &quot;.date(&quot;d/m/Y&quot;,$dema).&quot;</p> &quot;;
      • echo &quot;<p>31/2/2000&quot;;
      • if (checkdate(31, 2, 2000)) {
      • echo &quot;La data és correcte&quot;;
      • } else {
      • echo &quot;La data és incorrecte&quot;;
      • }
      • echo &quot;</p> &quot;;
    24. 2.10 Exemple senzill (I)
      • <?php
      • include ('../includes/capcaleres.php');
      • cap(&quot;Exemple 2: Operadors, instruccions, funcions i llibreries&quot;);
      • function factorial($n)
      • {
      • if ($n > 0){
      • $resultat=1;
      • for ($i=1;$i<$n;$i++){
      • $resultat=$resultat*($i+1);
      • }
      • return $resultat;
      • }
      • else return 1;
      • }
      • /*
      • * Mostra els nombres factorials entre 1 i $end
      • */
      • echo &quot;<div id=&quot;main&quot;><p> &quot;;
      • $i = 1;
      • $end = 10;
      • while ($i<=$end){
      • echo &quot;$i! = &quot;.factorial($i).&quot;<br /> &quot;;
      • $i++;
      • }
      • echo &quot;</p></div> &quot;;
      • peu();
      • ?>
      2.10 Exemple senzill (II)
    25. 2.11 Formularis form.php
      • METODES ENVIAMENT
      • 1. GET
        • Info petita
        • Codificada a la URL
      • 2. POST
        • Info petita o gran
        • Protocol HTTP
    26. 2.12 Control actualització cache client
      • Per què?
        • Per assegurar-nos que la web s’actualitza quan ens interessa
      • Com?
        • Com el navegador vulgui ( compte! )
          • - No ficar res
        • La web al cache del navegador té data de caducitat
          • <meta http-equiv=&quot;expires&quot;
          • content=&quot;Wed, 21 Jun 2006 14:25:27 GMT&quot; />
        • Cada vegada que l’usuari la consulti s’actualitzarà (sense cache navegador)
          • <meta http-equiv=&quot;pragma&quot; content=&quot;no-cache&quot; />
          • <meta http-equiv=&quot;cache-control&quot; content=&quot;no-cache,must-revalidate,proxy-revalidate&quot; />
    27. 3-Guardar info usuari
    28. 3.1 Cookies
      • Informació
        • Navegador usuari remot
        • Tamany
          • Petit
          • Limitat per navegador
      • Utilitat
        • Identificar (+guardar info) de l’usuari per quan torni
      • Crear
        • bool setcookie ($name,$value,$expire,$path,$domain,
        • $secure,$httponly)
        • <?php
        • setcookie(…)
        • echo “….”;
        • <?php
        • echo “….”;
        • setcookie(…); ERROR
      • Consulta
        • $var = $_COOKIE[“nomVar”]
      • Esborrar
        • $expire = UNIX Stamp ja passada
        • setcookie(…, $expire,…)
    29. 3.1 Cookies: Exemple
      • Llegir
        • if (isset($_COOKIE[&quot;user&quot;]))
        • echo &quot;Benvingut &quot;
        • .$_COOKIE['user'].
        • &quot;! <br />&quot;;
      • Crear
        • // Caducitat en 30 dies
        • $expire=time()+60*60*24*30;
        • // creacio de la cookie
        • if (setcookie(&quot;user&quot;,&quot;John Lenon&quot;,$expire,&quot;/tenda&quot;)){
        • echo&quot;<p>CookieSET!</p> &quot;;
        • }
      • Eliminar
        • <?php
        • // Eliminar cookie (ficar temps caducitat a una hora abans)
        • if (setcookie(&quot;user&quot;, &quot;&quot;, time()-3600,&quot;/tenda&quot;)){
        • echo &quot;<p>Cookie DELETED</p>&quot;;
        • }
    30. 3.2. Sessions
      • Definició
        • Similar a cookies però majoria d’informació es guarda al servidor
      • Crear
        • session_start();
        • $_SESSION[“var”]=[valor inici];
      • Consultar
        • session_start();
        • $var = $_SESSION[“var”];
      • Eliminar
        • Variable
          • session_start();
          • unset($_SESSION[“var”]);
        • Sessió
          • session_start();
          • session_destroy();
    31. 3.2 Sessions: Exemple
      • Crear i consultar
        • session_start();
        • if(isset($_SESSION['views']))
        • $_SESSION['views']=
        • $_SESSION['views']+1;
        • else
        • $_SESSION['views']=1;
        • echo &quot;<p>Pàgines vistes=&quot;. $_SESSION['views'].&quot;</p>&quot;;
      • Eliminar
        • session_start();
        • unset($_SESSION['views']);
        • session_unset();
        • session_destroy();
    32. 3.3 Session vs Cookies
      • Sessions
      • Gran quanitat informació
      • Ràpids
      • Informació pot ser consultada i modificada per altres (ja que per defecte es guarda a /tmp)
      • Centralitzat
      • Necessari hardware extra en clusters (servidor de fitxers centralitzat)
      • Necessita d’un petit cookie amb la sessionID
      • Cookies
      • Petita quantitat d’informació (màx 20 cookies 4K per domini)
      • Lents
      • Informació cookie pot ser modificada “fàcilment” per usuari
      • Distribuït
    33. 4- PHP   MYSQL
    34. Base de dades: Db_tenda
      • productes
      • proveidors
    35. 4.1 Exemple bàsic <? // conectem a la MYSQL $conn = mysql_connect(&quot;localhost&quot;.':'.'3306',&quot;root&quot;,“contrasenya&quot;); // Seleccionem la base de dades $db = mysql_select_db(&quot;db_tenda&quot;,$conn); // Fem la consulta $sql=sprintf(&quot;SELECT nom FROM proveidors;&quot;); // desem el resultat $result=mysql_query($sql,$conn); //pintem el resultat de la consulta while($row=mysql_fetch_assoc($result)){ echo $row['nom']; echo '<br>'; } //alliberem resultat mysql_free_result($result);?>
    36. 4.2 Exemples complexes http://localhost/ce/mysql/exemple2.php http://localhost/ce/mysql/exemple3.php
      • Modificar el php.ini
      • magic_quotes_gpc = On
      • Codi php:
      • stripslashes($variable);
      4.3 Caràcters extranys: (ex: l ’ arbre)
    37. 5-PHP  Javascript
    38. 5.1 Passar variables de Javascript a PHP <script> var nomJavascript = “Enric&quot; ; </script> <?php $nomPHP = &quot;<script document.write(nomJavascript)</script>&quot;; echo “nom = $nomPHP &quot;; ?> 5.2 Passar variables de PHP a Javascript <script> var nomJavascript = <?echo $nomPHP;?> </script>
    39. 6- Tractament de fitxers
    40. 6.1 Pujar fitxers al servidor
      • Formulari
      • Upload.php
      • <form enctype=&quot;multipart/form-data&quot; action=&quot;upload.php&quot; method=&quot;post&quot;>
      • <input type=&quot;hidden&quot; name=&quot;MAX_FILE_SIZE&quot; value=&quot;1000000&quot; />
      • Choose a file to upload: <input name=&quot;uploaded_file&quot; type=&quot;file&quot; />
      • <input type=&quot;submit&quot; value=&quot;Upload&quot; />
      • </form>
      php.ini file_uploads = On max_input_time = 90 upload_max_filesize = 10M post_max_size = 20M memory_limit = 30M
        • Informació fitxer a la variable global
          • $_FILES[]
      • Es puja a carpeta temporal del sistema (Cal moure’l a la carpeta corresponent)
      • Vigilar la seguretat
      • Veure exemple
    41. 6.2 Fitxers text plà (I)
      • Obrir
        • $f= fopen (“nom_doc”,”opcio”)
        • r/r+ = Mode lectura
        • w/w+ = Mode escriptura desde 0, si no existeix el crea
        • a/a+ = Mode escriptura continuada
      • Llegir
        • Binaris
          • fread($f,longitud)
        • Text:
          • fget ($f,longitud)
          • fgetcsv ($f, [longitud, delimitador])
      • Escriure
      • fwrite ($f, contingut)
      • Tancar
        • fclose ($f)
      • $nomdoc=“registers.txt&quot;;
      • $fp= fopen ($nomdoc,&quot;r&quot;);
      • $conta=0;
      • $total=0;
      • while (($data = fgetcsv($fp,1000,&quot;|&quot;)) !== FALSE){
      • foreach($data as $row) {
      • $conta++;
      • if ($conta==1) {
      • $dia[$total]=$row;
      • }
      • if ($conta==2) {
      • $mes[$total]=$row;
      • }
      • if ($conta==3) {
      • $any[$total]=$row;
      • $total++;
      • }
      • }
      • fclose($fp);
      • }
      Exemple: Registers.txt 6.2 Fitxers text plà (I)
    42. 6.3 Altres tipus de fitxers
      • PDF
        • Configurar php.ini per activar pdf_lib
        • Usar llibreria (veure exemple)
          • $pdf = pdf_new();
          • pdf_begin_page($pdf, 600, 800);
          • pdf_show_xy($pdf, &quot;Dire Straits - Brothers in arms&quot;, 100, 800);
          • pdf_end_page($pdf);
          • pdf_close($pdf);
      • Excel
        • Descarregar-se PEAR per php http:// pear.php.net /
        • Incorporar llibreria segons la operació que vulguem fer:
          • Escriptura
          • require_once('Spreadsheet/Excel/Writer.php');
          • Lectura
          • require_once('Spreadsheet/Excel/Reader.php');
        • Usar la llibreria (veure exemple)
    43. 7- Tractament de Mails
    44. 7.1 Enviar correus electrònics
      • Senzills (text)
        • mail($per, $asumpte, $missatge, $capceleres);
      • Complexes (fitxers adjunts,…)
        • MIME
          • Multipurpose Internet Mail Extensions
        • http :// www.phpguru.org / static / mime.mail.html
    45. 7.2. Exemple // Múltiples enviaments $per = 'aidan@example.com' . ','; // no te la coma $per.= 'wez@example.com'; // Assumpte $asumpte = ‘Recordatori aniversari'; // Missatge $missatge = ' <html> <head> <title> Recordatori aniversari agost</title> </head> <body> <p>Joan dia 20, Pere dia 30,…</p> </body> </html>'; // HTML necessari $capceleres = 'MIME-Version: 1.0' . &quot; &quot;; $capceleres.= 'Content-type: text/html; charset=iso-8859-1' . &quot; &quot;; //Capceleres adicionals $capceleres.= 'To: María <maria@exemple.com>, Kelly <kelly@exemple.com>' . &quot; &quot;; $capceleres.= 'From: Recordatori aniversari <recordatori@exemple.com>' . &quot; &quot;; $capceleres .= 'Cc: archiu@exemple.com'.&quot; &quot;; $capceleres .= 'Bcc: chequeig@exemple.com'.&quot; &quot;; // Enviament mail($per, $asumpte, $missatge, $capceleres);
    46. Moltes gràcies! Preguntes? http://tinyurl.com/presentation-comments

    + masamunemasamune, 2 years ago

    custom

    1827 views, 0 favs, 0 embeds more stats

    introducció a php

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 1827
      • 1827 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 28
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories