SlideShare a Scribd company logo
1 of 24
Download to read offline
PHP
  Personal Homepage Tools - Hypertext Preprocessor


  Programmieren für das Web

Teil 1 - Grundlagen

Version: 2012-04-17

License: CC BY NC SA

Erstellt von Hans-Joachim Piepereit (hajo_p@live.de)
Konstruktives Feedback hierzu ist gern gesehen
Inhaltsverzeichnis
1 Einführung                                                                                      3
  1.1 Geschichte . . . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    3
  1.2 Anwendungsbeispiele . .    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    5
  1.3 Funktionsweise . . . . .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .    7
  1.4 Installation und Extras    .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   .   10

2 Bausteine der Sprache                                                                          12
  2.1 Eigenschaften . . . . . . . .      .   .   .   .   .   .   .   .   .   .   .   .   .   .   12
  2.2 Syntax und Strukturen . .          .   .   .   .   .   .   .   .   .   .   .   .   .   .   13
  2.3 Gefahren und Stützräder . .        .   .   .   .   .   .   .   .   .   .   .   .   .   .   18
  2.4 Arbeit mit externen Daten .        .   .   .   .   .   .   .   .   .   .   .   .   .   .   20
  2.5 Argumentation . . . . . . .        .   .   .   .   .   .   .   .   .   .   .   .   .   .   23

3 Anhang                                                    24
  3.1 Verweise und Empfehlungen . . . . . . . . . . . . . . 24



                                 2
1 Einführung
1.1 Geschichte
PHP 1, 2
Rasmus Lerdorf

Personal Home Page Tools (1994 - 1997 )

PHP 3, 4
Rasmus Lerdorf, Zeev Suraski, Andi Gutmans

Zend Engine 1 (1999 - 2003 )




                               3
PHP 5
Zend Engine 2 (2004 - 2012 )

5.0   -   2004   -   Objektorientierung
5.1   -   2005   -   PDO (Datenbanken), SPL (Standard Werkzeugkiste)
5.2   -   2006   -   Filter (Validierung und Absicherung)
5.3   -   2009   -   Namensräume, PHAR Archive, Late Static Binding
5.4   -   2012   -   Mini Webserver, Traits, Wegfall alter Stützräder

PHP 6
Das Unicode Problem der Zend Engine 3 (ICU bzw. INTL)

Aktuell
- Versionskontrolle auf GitHub umgezogen
- Planungen für PHP 5.5 laufen (RFCs im Wiki)



                                        4
1.2 Anwendungsbeispiele
    Ursprung: In HTML eingebettete Template Sprache
1   <html><body>
2   <?php echo " H a l l o Welt " ; ?>
3   </body></html>


      Entwicklung: Trennung von Struktur (HTML) und Logik (PHP)
1   <html><body>
2   <?php i n c l u d e ' news . php ' ?>
3   </body></html>


1   <?php // news . php
2   echo " Dies i s t e i n e News <br />n " ;
3   echo " Dies i s t e i n e w e i t e r e News <br />n " ;




                                            5
MVC-Web: Zusätzliche Trennung von Logik und Daten in PHP
1    <?php
2    // S t a r t e Logik
3    $con = new php_framework F r o n t C o n t r o l l e r ( ) ;
4    // Verbinde mit D a t e n s p e i c h e r
5    $dao = new php_frameworkDAO( ' mysql ' ) ;
6    // Hole Daten ab
7    $data = $dao−        >user− i l t e r B y I d ( 1 ) ;
                                  >f
8    // S e t z e e i n e HTML Datei f u e r das Aussehen
9    $view = new php_frameworkView ( ' t e s t . htm ' ) ;
10   // Erzeuge d i e Ausgabe
11   $ r e s u l t = $view− a r s e ( $data ) ;
                             >p
12   // S e t z e d i e Ausgabe e i n
13   $con−    >setBody ( $ r e s u l t ) ;
14   // Sende Header und Ausgabe
15   $con−    >send ( ) ;

      Die Klassen sind je nach Framework anders benannt / strukturiert.



                                            6
1.3 Funktionsweise
Ablauf bei Standardverwendung
1. Request    Ansurfen von z.B. www.php.net/index.php

2. Webserver Annahme der Anfrage z.B. auf HTTP Port 80

3. PHP        Verarbeitet z.B. /var/www/localhost/index.php

4. Response PHP übergibt Resultat an Webserver zur Antwort

5. Ausgabe    Browser stellt die Antwort dar (z.B. in HTML)

 Beachte: HTTP ist zustandslos, Sitzungen in PHP nutzbar

 Webserver für PHP: Apache, Lighttpd, Microsoft IIS, Nginx, ...




                               7
Ablauf bei Kommandozeile
1. Kommando Ausführen von z.B. php /dev/php/test.php

2. PHP         Verarbeitet die Datei im besonderen CLI Modus

3. Ausgabe     Resultat folgt direkt aus PHP heraus

Beispiele für Kommandozeilen: Windows CMD, Linux Bash Shell

Beispiele für Verwendung: PHP PEAR, PHP Server, PHP Tools

Details zum Compiler
   On the fly      Single Request      Verbose

Opcode Caching    Shared Memory     Zend Guard




                              8
Bereiche starten und beenden

     *.php    Standard für auszuführende Dateien
     *.phps   Quelltext der Datei mit Syntaxhervorhebung


1    // Standard
2    <?php
3    // Short open tag ( Achtung b e i XML)
4    <?
5    // Short echo syntax ( s e i t 5 . 4 Standard s t a t t Short )
6    <?= " H a l l o Welt "
7    // C l o s i n g tag (am Dateiende w e g l a s s b a r )
8    ?>
9    // S c r i p t V a r i a n t e ( v e r a l t e t )
10   <s c r i p t language=" php "></s c r i p t >




                                       9
1.4 Installation und Extras
Die passende Version bestimmen
- VC9 besser und schneller als VC6, NTS besser als TS
- Apache MPM Variante mit mod_php effektivste Umgebung

  Thread Sicherheit   Ja (TS)             Nein (NTS)
  Verwendung          Multi-Threading     Kein Threading
  Beispiel            Apache MPM worker   Apache MPM prefork
  Vorteile            Mehr Sicherheit     Stabiler und Performanter

Built-in Development Server
Kommandozeile php -S Adresse:Port
Beispiel: php -S localhost:8080




                              10
Konfiguration
- php.ini im PHP Verzeichnis
- Webserver (z.B. Apache .htaccess)
- PHP Befehle ini_* mit z.B. ini_set

  Hinweis: extension_dir = "./ext" geht auch unter Windows

PECL
PHP Extension Community Library
Bezug von Erweiterungen (z.B. APC, Imagick, Xdebug)

PEAR
PHP Extension and Application Repository
Bezug von vorgefertigten Klassen (z.B. PEAR DB, PEAR Mail)




                               11
2 Bausteine der Sprache
2.1 Eigenschaften
Herkunft und Einfluss
Imperativ nah bei C und teilweise Perl, Objektorientiert nah bei Java
Stellt viele C Bibliotheken als leicht nutzbare Erweiterungen bereit

Typisierung
Dynamisch und schwach, per SPL bedingt erzwingbar
Typ bei formalen Parametern nur für Arrays und Objekte
Einfache Typen z.B. per settype Anweisung wechselbar

Einordnung
Programmiersprache, Scriptsprache, Imperativ, Objektorientiert



                                 12
2.2 Syntax und Strukturen
    Ausgabe von Text

1   <?php // Zuweisung e i n e s Wertes b e i der V a r i a b l e t e s t
2   $ t e s t = ' Test ' ;
3   // Der Punkt−Operator v e r b i n d e t I n h a l t e m i t e i n a n d e r
4   echo ' Dies i s t ' . " nur e i n " . $ t e s t ;



    Rechnen

1   <?php
2   $ z a h l = FALSE ;
3   // Addiere 1 hinzu und forme dadurch zum I n t e g e r um
4   $ z a h l += 1 ; # A l t e r n a t i v e n : $ z a h l++ oder ++$ z a h l
5   // S t e l l e s i c h e r , d a s s Zahl a l s I n t e g e r verwendet wird
6   echo ' Zahl : ' . ( i n t ) $ z a h l ;




                                           13
Arrays
    Sind in PHP sehr vielfältig einsetzbar (noch mehr mit SPL)

            Map                  List            Stack

       Dictionary           Collection          Queue


1    <?php
2    // S p e i c h e r e mehrere Farben i n e i n e r V a r i a b l e
3    $ c o l o r s = a r r a y ( ' red ' , ' g r e e n ' , ' y e l l o w ' ) ;
4

5    // Mehrere Dimensionen v e r s c h a c h t e l b a r
6    $ t e s t = a r r a y ( a r r a y ( ' t e s t ' => a r r a y ( ) ) ) ;
7

8    // S e i t PHP 5 . 4 : Short a r r a y syntax
9    $ c o l o r s = [ ' red ' , ' g r e e n ' , ' y e l l o w ' ] ;




                                                     14
Man kann sehr dynamisch und flexibel mit Arrays arbeiten


1    <?php
2    $array = array () ;
3

4    // Neue Elemente a n l e g e n
5    $array [ ] = ' eintrag 1 ' ;
6    $array [ ] = ' eintrag 2 ' ;
7

8    // Lese das e r s t e Element aus
9    $one = $ a r r a y [ 0 ] ;
10

11   // S o r t i e r e d i e Elemente im Array nach Keys
12   ksort ( $array ) ;
13

14   // E n t f e r n e e i n Element aus einem Array
15   unset ( $array [ 0 ] ) ;




                                      15
Funktionen

1    <?php
2    // Addiere 1 dazu
3    f u n c t i o n my_inc ( $ i n t ) { r e t u r n ++$ i n t ; }
4    // Teste d i e Funktion
5    echo my_inc ( 1 ) ;
6    // Funktion per C a l l b a c k verwenden
7    echo c a l l _ u s e r _ f u n c ( ' my_inc ' , 1) ;
8

9     // S e l b i g e s a l s Anonyme Funktion ( C l o s u r e )
10    $my_inc = f u n c t i o n ( $ i n t ) { r e t u r n ++$ i n t ; }
11    // Teste d i e Funktion
12    echo $my_inc ( 2 ) ;
13    // Anonyme Funktion per C a l l b a c k verwenden
14    echo c a l l _ u s e r _ f u n c ( $my_inc , 2) ;




                                               16
Verzweigungen

1   <?php // Wenn Dann
2   i f (1 === TRUE) { echo ' 1 i s t genau TRUE' } ;
3   // A l t e r n a t i v e
4   e l s e i f (1 == TRUE) { echo ' 1 i s t sowas wie TRUE' ; }
5   // Sonst
6   e l s e { echo ' 1 i s t n i c h t TRUE' } ;



    Schleifen

1   <?php // For−S c h l e i f e ( e t w a i g wie i n C)
2   f o r ( $ i = 0 ; $ i < 1 0 ; $ i++) { echo $ i . ' ' ; }
3

4    // Foreach−S c h l e i f e ( s e h r g e e i g n e t b e i Arrays )
5    f o r e a c h ( $ a r r a y AS $key => $ v a l u e ) { echo '~ ' ; }




                                            17
2.3 Gefahren und Stützräder
Globale Werte und Input-Daten
Typ                Beispiele             Bemerkungen
Globals            $GLOBALS[’var’]       Unsauber und seit 5.4 JIT
Global Import      global $var           Etwaig wie Globals
Superglobals       $_GET[’id’]           Nicht ungefiltert verwenden
Register Globals   $_GET[’id’] als $id   Seit 5.4 entfernt

Strings und Anführungszeichen
Typ            Beispiele                   Bemerkungen
Null Byte      0 oder %00                 Wirkt anders als man denkt
Bearbeitung    substr($var)                Besser iconv_substr($var)
Magic Quotes   $_POST mit addslashes       Seit 5.4 entfernt
Encoding       Byte order mark             Mag PHP nicht leiden




                                18
Weiteres
Typ             Beispiele                Bemerkungen
64 bit builds   amd64                    Noch nicht ausgereift
Threads         Multi-Threading          Siehe Abschnitt Installation
Eval            eval(’php sourcecode’)   Viel Spaß beim absichern
Safe Mode       Künstliche Verbote       Seit 5.4 entfernt

Abhilfen
Typ              Beispiele          Bemerkungen
SQL Injection    Quotes, Union      Prepared Statements (PDO)
Remote Exec      include $file       allow_url_include deaktivieren
 Headers send    echo vor header    Ausgabepuffer (ob_*)

Erweiterung der Sicherheit:

PECL taint, Suhosin Patch, open_basedir, display_errors, ...



                                   19
2.4 Arbeit mit externen Daten
     Superglobals

1    <?php // D e t a i l s zum S e r v e r und dem Anfrage−Z i e l
2    $_SERVER
3    // HTTP GET Daten
4    $_GET
5    // HTTP POST Daten
6    $_POST
7    // M u l t i p a r t Daten
8    $_FILES
9    // Cookies s e t z e n und a b r u f e n
10    s e t c o o k i e ( ' name ' , ' i n h a l t ' ) ;
11   $_COOKIE
12   // S e s s i o n s t a r t e n und verwenden
13    session_start ()
14   $_SESSION




                                        20
Dateisystem

1    <?php
2    // Lese den I n h a l t e i n e r Datei e i n
3    $text = file_get_contents ( ' test . txt ' ) ;
4

5     // S c h r e i b e den I n h a l t i n e i n e andere Datei
6     file_put_contents ( ' test2 . txt ' , $text ) ;
7

8     // Das   Lesen geht z .B. auch per URI
9     $uri     = u r l e n c o d e ( ' http : / /www. php . net / index . php ' ) ;
10    $text2   = file_get_contents ( $uri ) ;
11    /∗
12     ∗ Man   s o l l t e b e i URIs immer u r l e n c o d e verwenden
13     ∗ und   vor e i n e r Ausgabe den I n h a l t a b s i c h e r n
14     ∗/




                                               21
User Memory Cache (KeyValueStore)

1    <?php $ r e s u l t = ' ' ;
2    // Check a u f E x i s t e n z der Erweiterung
3    i f ( e x t e n s i o n _ l o a d e d ( ' xcache ' ) ) {
4

5        // S p e i c h e r e e i n e n E i n t r a g 30 Sekunden l a n g
6        xcache_set ( ' key ' , ' t e s t v a l u e ' , 30) ;
7

8        // Lade den E i n t r a g
9        i f ( x c a c h e _ i s s e t ( ' key ' ) ) {
10

11           $ r e s u l t = xcache_get ( ' key ' ) ;
12       }
13   }
14

15    echo ' Cache I n h a l t : ' . $ r e s u l t ;




                                                         22
2.5 Argumentation
Vorteile
- Sehr gut dokumentiert, einfach zu Lernen, schnelle Resultate
- Flexibel verwendbar, Plattformunabhängig, alles Wichtige dabei
- Hochgradig skalierbar, leichtes Deployment, Cloud Betrieb möglich
- Direkter und vollständiger Support von HTTP und der Server-API
- Durchdachte Einteilung von Sichtbarkeitsbereichen der Variablen
- Keine laufende Anwendung nötig, wird gestartet und verworfen

Nachteile
- Schnelle Resultate führen zu Fehlern und schlechter Code Qualität
- Historisch gewachsen, daher teilweise mehrere Wege für ein Ziel
- PHP Erweiterungen untereinander sehr unterschiedlich aufgebaut
- Strings werden nur Byte-basiert verwendet (Abhilfen vorhanden)
- Fehlende Features treiben Enterprise Frameworks in Workarounds



                                23
3 Anhang
3.1 Verweise und Empfehlungen
Websites zu den Themen
http://www.php.net/manual             PHP Manual
http://pear.php.net                   PHP PEAR
http://pecl.php.net                   PHP PECL
http://www.hardened-php.net/suhosin   Suhosin Patch
http://httpd.apache.org               Apache Webserver
http://www.apachelounge.com           Apache for Windows
http://xcache.lighttpd.net            XCache Extension

Bücher zu den Themen
Programming PHP O’Reilly    Der Klassiker von Rasmus Lerdorf
PHP 5 Kochbuch O’Reilly     Lösungswege für gängige Aufgaben




                            24

More Related Content

What's hot

Von Automaten zu Programmen–Parsergeneratoren und Attributgrammatiken
Von Automaten zu Programmen–Parsergeneratoren und AttributgrammatikenVon Automaten zu Programmen–Parsergeneratoren und Attributgrammatiken
Von Automaten zu Programmen–Parsergeneratoren und AttributgrammatikenTim Furche
 
Interprozesskommunikation mit PHP
Interprozesskommunikation mit PHPInterprozesskommunikation mit PHP
Interprozesskommunikation mit PHPStephan Schmidt
 
Lösungsorientierte Fehlerbehandlung
Lösungsorientierte FehlerbehandlungLösungsorientierte Fehlerbehandlung
Lösungsorientierte Fehlerbehandlungroskakori
 
P6kontext2014
P6kontext2014P6kontext2014
P6kontext2014lichtkind
 
Check cisco voice
Check cisco voiceCheck cisco voice
Check cisco voicebboguhn
 
Source Code Analyse - Ein praktikabler Ansatz
Source Code Analyse - Ein praktikabler AnsatzSource Code Analyse - Ein praktikabler Ansatz
Source Code Analyse - Ein praktikabler AnsatzMarc Ruef
 
Die freie Programmiersprache Python
Die freie Programmiersprache Python Die freie Programmiersprache Python
Die freie Programmiersprache Python Andreas Schreiber
 
Quellcode Analyse
Quellcode AnalyseQuellcode Analyse
Quellcode AnalyseAmir Neziri
 
Tech Talk: Groovy
Tech Talk: GroovyTech Talk: Groovy
Tech Talk: Groovymwie
 
IPC 2015 Zend Framework 3 Reloaded
IPC 2015 Zend Framework 3 ReloadedIPC 2015 Zend Framework 3 Reloaded
IPC 2015 Zend Framework 3 ReloadedRalf Eggert
 
Designpatterns in Ruby
Designpatterns in RubyDesignpatterns in Ruby
Designpatterns in Rubypfleidi
 
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...gedoplan
 
GNU Bourne Again SHell
GNU Bourne Again SHellGNU Bourne Again SHell
GNU Bourne Again SHellFabian Becker
 
GE_: mein perlsProgrammssprache Unterricht Vol.IV
GE_: mein perlsProgrammssprache Unterricht Vol.IVGE_: mein perlsProgrammssprache Unterricht Vol.IV
GE_: mein perlsProgrammssprache Unterricht Vol.IVgiovanni Colombo
 
IPC2017SE - Zend\Expressive Workshop
IPC2017SE - Zend\Expressive WorkshopIPC2017SE - Zend\Expressive Workshop
IPC2017SE - Zend\Expressive WorkshopRalf Eggert
 
Mozilla Audio Data API
Mozilla Audio Data API Mozilla Audio Data API
Mozilla Audio Data API Mayflower GmbH
 

What's hot (20)

Von Automaten zu Programmen–Parsergeneratoren und Attributgrammatiken
Von Automaten zu Programmen–Parsergeneratoren und AttributgrammatikenVon Automaten zu Programmen–Parsergeneratoren und Attributgrammatiken
Von Automaten zu Programmen–Parsergeneratoren und Attributgrammatiken
 
Interprozesskommunikation mit PHP
Interprozesskommunikation mit PHPInterprozesskommunikation mit PHP
Interprozesskommunikation mit PHP
 
Lösungsorientierte Fehlerbehandlung
Lösungsorientierte FehlerbehandlungLösungsorientierte Fehlerbehandlung
Lösungsorientierte Fehlerbehandlung
 
P6oo
P6ooP6oo
P6oo
 
P6kontext2014
P6kontext2014P6kontext2014
P6kontext2014
 
Check cisco voice
Check cisco voiceCheck cisco voice
Check cisco voice
 
Source Code Analyse - Ein praktikabler Ansatz
Source Code Analyse - Ein praktikabler AnsatzSource Code Analyse - Ein praktikabler Ansatz
Source Code Analyse - Ein praktikabler Ansatz
 
Die freie Programmiersprache Python
Die freie Programmiersprache Python Die freie Programmiersprache Python
Die freie Programmiersprache Python
 
Quellcode Analyse
Quellcode AnalyseQuellcode Analyse
Quellcode Analyse
 
Tech Talk: Groovy
Tech Talk: GroovyTech Talk: Groovy
Tech Talk: Groovy
 
IPC 2015 Zend Framework 3 Reloaded
IPC 2015 Zend Framework 3 ReloadedIPC 2015 Zend Framework 3 Reloaded
IPC 2015 Zend Framework 3 Reloaded
 
Ein Gopher im Netz
Ein Gopher im NetzEin Gopher im Netz
Ein Gopher im Netz
 
Designpatterns in Ruby
Designpatterns in RubyDesignpatterns in Ruby
Designpatterns in Ruby
 
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
Battle of the Languages: Java und Python im Wettstreit beim Lösen von Program...
 
Php Schulung
Php SchulungPhp Schulung
Php Schulung
 
GNU Bourne Again SHell
GNU Bourne Again SHellGNU Bourne Again SHell
GNU Bourne Again SHell
 
GE_: mein perlsProgrammssprache Unterricht Vol.IV
GE_: mein perlsProgrammssprache Unterricht Vol.IVGE_: mein perlsProgrammssprache Unterricht Vol.IV
GE_: mein perlsProgrammssprache Unterricht Vol.IV
 
IPC2017SE - Zend\Expressive Workshop
IPC2017SE - Zend\Expressive WorkshopIPC2017SE - Zend\Expressive Workshop
IPC2017SE - Zend\Expressive Workshop
 
Tutorium 4
Tutorium 4Tutorium 4
Tutorium 4
 
Mozilla Audio Data API
Mozilla Audio Data API Mozilla Audio Data API
Mozilla Audio Data API
 

Viewers also liked

Sirenita quería cantar
Sirenita quería cantarSirenita quería cantar
Sirenita quería cantarclau on
 
Actores que saben lo que hacen
Actores que saben lo que hacenActores que saben lo que hacen
Actores que saben lo que hacenanapunzon
 
H O T E L E S L A S V E G A S
H O T E L E S    L A S  V E G A SH O T E L E S    L A S  V E G A S
H O T E L E S L A S V E G A SJorge Llosa
 
A eso, llamalo.....
A eso, llamalo.....A eso, llamalo.....
A eso, llamalo.....Jorge Llosa
 
Tu angel - El otro yo
Tu angel - El otro yoTu angel - El otro yo
Tu angel - El otro yotiima
 
Inteco
IntecoInteco
Intecoyosko
 
Katalog náhradních dílů Movera, Hykro 2013/2014
Katalog náhradních dílů Movera, Hykro 2013/2014Katalog náhradních dílů Movera, Hykro 2013/2014
Katalog náhradních dílů Movera, Hykro 2013/2014hykro
 
Presentacion de la asoc. fibrocastril
Presentacion de la asoc. fibrocastrilPresentacion de la asoc. fibrocastril
Presentacion de la asoc. fibrocastrilCristina Gómez
 
Enfoquecuantitativoycualitativoenlainvestigacin 120410165102-phpapp01
Enfoquecuantitativoycualitativoenlainvestigacin 120410165102-phpapp01Enfoquecuantitativoycualitativoenlainvestigacin 120410165102-phpapp01
Enfoquecuantitativoycualitativoenlainvestigacin 120410165102-phpapp01Milagros Rodriguez
 
Sonata claro de luna
Sonata claro de lunaSonata claro de luna
Sonata claro de lunaJorge Llosa
 
Encuesta Discapacidad, AutonomíA Y Dependencia
Encuesta Discapacidad, AutonomíA Y DependenciaEncuesta Discapacidad, AutonomíA Y Dependencia
Encuesta Discapacidad, AutonomíA Y DependenciaProfesorachapela
 

Viewers also liked (20)

Sirenita quería cantar
Sirenita quería cantarSirenita quería cantar
Sirenita quería cantar
 
Valentín
ValentínValentín
Valentín
 
Observatorio de Calidad
Observatorio de CalidadObservatorio de Calidad
Observatorio de Calidad
 
Actores que saben lo que hacen
Actores que saben lo que hacenActores que saben lo que hacen
Actores que saben lo que hacen
 
H O T E L E S L A S V E G A S
H O T E L E S    L A S  V E G A SH O T E L E S    L A S  V E G A S
H O T E L E S L A S V E G A S
 
1 a
1 a1 a
1 a
 
ABUELA
ABUELAABUELA
ABUELA
 
Acuarelas
AcuarelasAcuarelas
Acuarelas
 
A eso, llamalo.....
A eso, llamalo.....A eso, llamalo.....
A eso, llamalo.....
 
la amistad
la amistadla amistad
la amistad
 
Tu angel - El otro yo
Tu angel - El otro yoTu angel - El otro yo
Tu angel - El otro yo
 
Inteco
IntecoInteco
Inteco
 
Katalog náhradních dílů Movera, Hykro 2013/2014
Katalog náhradních dílů Movera, Hykro 2013/2014Katalog náhradních dílů Movera, Hykro 2013/2014
Katalog náhradních dílů Movera, Hykro 2013/2014
 
SEGOVIA
SEGOVIASEGOVIA
SEGOVIA
 
Presentacion de la asoc. fibrocastril
Presentacion de la asoc. fibrocastrilPresentacion de la asoc. fibrocastril
Presentacion de la asoc. fibrocastril
 
Enfoquecuantitativoycualitativoenlainvestigacin 120410165102-phpapp01
Enfoquecuantitativoycualitativoenlainvestigacin 120410165102-phpapp01Enfoquecuantitativoycualitativoenlainvestigacin 120410165102-phpapp01
Enfoquecuantitativoycualitativoenlainvestigacin 120410165102-phpapp01
 
Sonata claro de luna
Sonata claro de lunaSonata claro de luna
Sonata claro de luna
 
LA FOTOGRAFÍA
LA FOTOGRAFÍALA FOTOGRAFÍA
LA FOTOGRAFÍA
 
Firstclass
FirstclassFirstclass
Firstclass
 
Encuesta Discapacidad, AutonomíA Y Dependencia
Encuesta Discapacidad, AutonomíA Y DependenciaEncuesta Discapacidad, AutonomíA Y Dependencia
Encuesta Discapacidad, AutonomíA Y Dependencia
 

Similar to Web Entwicklung mit PHP - Teil 1

Why websecurity sucks
Why websecurity sucksWhy websecurity sucks
Why websecurity sucksThaDafinser
 
OSMC 2008 | Programmierung von Nagios-Plugins für NetApp Speichergeräte by In...
OSMC 2008 | Programmierung von Nagios-Plugins für NetApp Speichergeräte by In...OSMC 2008 | Programmierung von Nagios-Plugins für NetApp Speichergeräte by In...
OSMC 2008 | Programmierung von Nagios-Plugins für NetApp Speichergeräte by In...NETWAYS
 
Source-Code-Analyse – ein praktikabler Ansatz
Source-Code-Analyse – ein praktikabler AnsatzSource-Code-Analyse – ein praktikabler Ansatz
Source-Code-Analyse – ein praktikabler AnsatzDigicomp Academy AG
 
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins Christian Kauhaus
 
JAX 2024: Go in der Praxis einsetzen
JAX 2024: Go in der Praxis einsetzenJAX 2024: Go in der Praxis einsetzen
JAX 2024: Go in der Praxis einsetzenJan Stamer
 
Coffee Backone Introduction
Coffee Backone IntroductionCoffee Backone Introduction
Coffee Backone IntroductionTino Isnich
 
Go - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeGo - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeFrank Müller
 
Object-orientied way of using mysqli interface - Workshop
Object-orientied way of using mysqli interface - WorkshopObject-orientied way of using mysqli interface - Workshop
Object-orientied way of using mysqli interface - WorkshopWaldemar Dell
 
Drupal 8: TWIG Template Engine
Drupal 8:  TWIG Template EngineDrupal 8:  TWIG Template Engine
Drupal 8: TWIG Template Enginedrubb
 
Top 10 Internet Trends 2003
Top 10 Internet Trends 2003Top 10 Internet Trends 2003
Top 10 Internet Trends 2003Jürg Stuker
 
Jpgraph - eine Einführung
Jpgraph - eine EinführungJpgraph - eine Einführung
Jpgraph - eine Einführungfrankstaude
 
Übersicht Skriptsprachen
Übersicht SkriptsprachenÜbersicht Skriptsprachen
Übersicht SkriptsprachenA. LE
 
Log::Log4perl qw/:easy/
Log::Log4perl qw/:easy/Log::Log4perl qw/:easy/
Log::Log4perl qw/:easy/Thomas Fahle
 

Similar to Web Entwicklung mit PHP - Teil 1 (20)

Why websecurity sucks
Why websecurity sucksWhy websecurity sucks
Why websecurity sucks
 
Web Entwicklung mit PHP - Teil 3 Beta
Web Entwicklung mit PHP - Teil 3 BetaWeb Entwicklung mit PHP - Teil 3 Beta
Web Entwicklung mit PHP - Teil 3 Beta
 
OSMC 2008 | Programmierung von Nagios-Plugins für NetApp Speichergeräte by In...
OSMC 2008 | Programmierung von Nagios-Plugins für NetApp Speichergeräte by In...OSMC 2008 | Programmierung von Nagios-Plugins für NetApp Speichergeräte by In...
OSMC 2008 | Programmierung von Nagios-Plugins für NetApp Speichergeräte by In...
 
Einsteiger Workshop
Einsteiger WorkshopEinsteiger Workshop
Einsteiger Workshop
 
Source-Code-Analyse – ein praktikabler Ansatz
Source-Code-Analyse – ein praktikabler AnsatzSource-Code-Analyse – ein praktikabler Ansatz
Source-Code-Analyse – ein praktikabler Ansatz
 
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
nagiosplugin - eine Python-Biblioth­ek für Monitoring-Plug­ins
 
JAX 2024: Go in der Praxis einsetzen
JAX 2024: Go in der Praxis einsetzenJAX 2024: Go in der Praxis einsetzen
JAX 2024: Go in der Praxis einsetzen
 
Coffee Backone Introduction
Coffee Backone IntroductionCoffee Backone Introduction
Coffee Backone Introduction
 
PHP Sucks?!
PHP Sucks?!PHP Sucks?!
PHP Sucks?!
 
Ruby on Rails SS09 04
Ruby on Rails SS09 04Ruby on Rails SS09 04
Ruby on Rails SS09 04
 
Go - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare SystemeGo - Googles Sprache für skalierbare Systeme
Go - Googles Sprache für skalierbare Systeme
 
FLOW3-Workshop F3X12
FLOW3-Workshop F3X12FLOW3-Workshop F3X12
FLOW3-Workshop F3X12
 
Object-orientied way of using mysqli interface - Workshop
Object-orientied way of using mysqli interface - WorkshopObject-orientied way of using mysqli interface - Workshop
Object-orientied way of using mysqli interface - Workshop
 
Drupal 8: TWIG Template Engine
Drupal 8:  TWIG Template EngineDrupal 8:  TWIG Template Engine
Drupal 8: TWIG Template Engine
 
Top 10 Internet Trends 2003
Top 10 Internet Trends 2003Top 10 Internet Trends 2003
Top 10 Internet Trends 2003
 
Jpgraph - eine Einführung
Jpgraph - eine EinführungJpgraph - eine Einführung
Jpgraph - eine Einführung
 
Web-Services mit Go
Web-Services mit GoWeb-Services mit Go
Web-Services mit Go
 
Webapplikationen mit Node.js
Webapplikationen mit Node.jsWebapplikationen mit Node.js
Webapplikationen mit Node.js
 
Übersicht Skriptsprachen
Übersicht SkriptsprachenÜbersicht Skriptsprachen
Übersicht Skriptsprachen
 
Log::Log4perl qw/:easy/
Log::Log4perl qw/:easy/Log::Log4perl qw/:easy/
Log::Log4perl qw/:easy/
 

Web Entwicklung mit PHP - Teil 1

  • 1. PHP Personal Homepage Tools - Hypertext Preprocessor Programmieren für das Web Teil 1 - Grundlagen Version: 2012-04-17 License: CC BY NC SA Erstellt von Hans-Joachim Piepereit (hajo_p@live.de) Konstruktives Feedback hierzu ist gern gesehen
  • 2. Inhaltsverzeichnis 1 Einführung 3 1.1 Geschichte . . . . . . . . . . . . . . . . . . . . . . . 3 1.2 Anwendungsbeispiele . . . . . . . . . . . . . . . . . . 5 1.3 Funktionsweise . . . . . . . . . . . . . . . . . . . . . 7 1.4 Installation und Extras . . . . . . . . . . . . . . . . 10 2 Bausteine der Sprache 12 2.1 Eigenschaften . . . . . . . . . . . . . . . . . . . . . . 12 2.2 Syntax und Strukturen . . . . . . . . . . . . . . . . 13 2.3 Gefahren und Stützräder . . . . . . . . . . . . . . . . 18 2.4 Arbeit mit externen Daten . . . . . . . . . . . . . . . 20 2.5 Argumentation . . . . . . . . . . . . . . . . . . . . . 23 3 Anhang 24 3.1 Verweise und Empfehlungen . . . . . . . . . . . . . . 24 2
  • 3. 1 Einführung 1.1 Geschichte PHP 1, 2 Rasmus Lerdorf Personal Home Page Tools (1994 - 1997 ) PHP 3, 4 Rasmus Lerdorf, Zeev Suraski, Andi Gutmans Zend Engine 1 (1999 - 2003 ) 3
  • 4. PHP 5 Zend Engine 2 (2004 - 2012 ) 5.0 - 2004 - Objektorientierung 5.1 - 2005 - PDO (Datenbanken), SPL (Standard Werkzeugkiste) 5.2 - 2006 - Filter (Validierung und Absicherung) 5.3 - 2009 - Namensräume, PHAR Archive, Late Static Binding 5.4 - 2012 - Mini Webserver, Traits, Wegfall alter Stützräder PHP 6 Das Unicode Problem der Zend Engine 3 (ICU bzw. INTL) Aktuell - Versionskontrolle auf GitHub umgezogen - Planungen für PHP 5.5 laufen (RFCs im Wiki) 4
  • 5. 1.2 Anwendungsbeispiele Ursprung: In HTML eingebettete Template Sprache 1 <html><body> 2 <?php echo " H a l l o Welt " ; ?> 3 </body></html> Entwicklung: Trennung von Struktur (HTML) und Logik (PHP) 1 <html><body> 2 <?php i n c l u d e ' news . php ' ?> 3 </body></html> 1 <?php // news . php 2 echo " Dies i s t e i n e News <br />n " ; 3 echo " Dies i s t e i n e w e i t e r e News <br />n " ; 5
  • 6. MVC-Web: Zusätzliche Trennung von Logik und Daten in PHP 1 <?php 2 // S t a r t e Logik 3 $con = new php_framework F r o n t C o n t r o l l e r ( ) ; 4 // Verbinde mit D a t e n s p e i c h e r 5 $dao = new php_frameworkDAO( ' mysql ' ) ; 6 // Hole Daten ab 7 $data = $dao− >user− i l t e r B y I d ( 1 ) ; >f 8 // S e t z e e i n e HTML Datei f u e r das Aussehen 9 $view = new php_frameworkView ( ' t e s t . htm ' ) ; 10 // Erzeuge d i e Ausgabe 11 $ r e s u l t = $view− a r s e ( $data ) ; >p 12 // S e t z e d i e Ausgabe e i n 13 $con− >setBody ( $ r e s u l t ) ; 14 // Sende Header und Ausgabe 15 $con− >send ( ) ; Die Klassen sind je nach Framework anders benannt / strukturiert. 6
  • 7. 1.3 Funktionsweise Ablauf bei Standardverwendung 1. Request Ansurfen von z.B. www.php.net/index.php 2. Webserver Annahme der Anfrage z.B. auf HTTP Port 80 3. PHP Verarbeitet z.B. /var/www/localhost/index.php 4. Response PHP übergibt Resultat an Webserver zur Antwort 5. Ausgabe Browser stellt die Antwort dar (z.B. in HTML) Beachte: HTTP ist zustandslos, Sitzungen in PHP nutzbar Webserver für PHP: Apache, Lighttpd, Microsoft IIS, Nginx, ... 7
  • 8. Ablauf bei Kommandozeile 1. Kommando Ausführen von z.B. php /dev/php/test.php 2. PHP Verarbeitet die Datei im besonderen CLI Modus 3. Ausgabe Resultat folgt direkt aus PHP heraus Beispiele für Kommandozeilen: Windows CMD, Linux Bash Shell Beispiele für Verwendung: PHP PEAR, PHP Server, PHP Tools Details zum Compiler On the fly Single Request Verbose Opcode Caching Shared Memory Zend Guard 8
  • 9. Bereiche starten und beenden *.php Standard für auszuführende Dateien *.phps Quelltext der Datei mit Syntaxhervorhebung 1 // Standard 2 <?php 3 // Short open tag ( Achtung b e i XML) 4 <? 5 // Short echo syntax ( s e i t 5 . 4 Standard s t a t t Short ) 6 <?= " H a l l o Welt " 7 // C l o s i n g tag (am Dateiende w e g l a s s b a r ) 8 ?> 9 // S c r i p t V a r i a n t e ( v e r a l t e t ) 10 <s c r i p t language=" php "></s c r i p t > 9
  • 10. 1.4 Installation und Extras Die passende Version bestimmen - VC9 besser und schneller als VC6, NTS besser als TS - Apache MPM Variante mit mod_php effektivste Umgebung Thread Sicherheit Ja (TS) Nein (NTS) Verwendung Multi-Threading Kein Threading Beispiel Apache MPM worker Apache MPM prefork Vorteile Mehr Sicherheit Stabiler und Performanter Built-in Development Server Kommandozeile php -S Adresse:Port Beispiel: php -S localhost:8080 10
  • 11. Konfiguration - php.ini im PHP Verzeichnis - Webserver (z.B. Apache .htaccess) - PHP Befehle ini_* mit z.B. ini_set Hinweis: extension_dir = "./ext" geht auch unter Windows PECL PHP Extension Community Library Bezug von Erweiterungen (z.B. APC, Imagick, Xdebug) PEAR PHP Extension and Application Repository Bezug von vorgefertigten Klassen (z.B. PEAR DB, PEAR Mail) 11
  • 12. 2 Bausteine der Sprache 2.1 Eigenschaften Herkunft und Einfluss Imperativ nah bei C und teilweise Perl, Objektorientiert nah bei Java Stellt viele C Bibliotheken als leicht nutzbare Erweiterungen bereit Typisierung Dynamisch und schwach, per SPL bedingt erzwingbar Typ bei formalen Parametern nur für Arrays und Objekte Einfache Typen z.B. per settype Anweisung wechselbar Einordnung Programmiersprache, Scriptsprache, Imperativ, Objektorientiert 12
  • 13. 2.2 Syntax und Strukturen Ausgabe von Text 1 <?php // Zuweisung e i n e s Wertes b e i der V a r i a b l e t e s t 2 $ t e s t = ' Test ' ; 3 // Der Punkt−Operator v e r b i n d e t I n h a l t e m i t e i n a n d e r 4 echo ' Dies i s t ' . " nur e i n " . $ t e s t ; Rechnen 1 <?php 2 $ z a h l = FALSE ; 3 // Addiere 1 hinzu und forme dadurch zum I n t e g e r um 4 $ z a h l += 1 ; # A l t e r n a t i v e n : $ z a h l++ oder ++$ z a h l 5 // S t e l l e s i c h e r , d a s s Zahl a l s I n t e g e r verwendet wird 6 echo ' Zahl : ' . ( i n t ) $ z a h l ; 13
  • 14. Arrays Sind in PHP sehr vielfältig einsetzbar (noch mehr mit SPL) Map List Stack Dictionary Collection Queue 1 <?php 2 // S p e i c h e r e mehrere Farben i n e i n e r V a r i a b l e 3 $ c o l o r s = a r r a y ( ' red ' , ' g r e e n ' , ' y e l l o w ' ) ; 4 5 // Mehrere Dimensionen v e r s c h a c h t e l b a r 6 $ t e s t = a r r a y ( a r r a y ( ' t e s t ' => a r r a y ( ) ) ) ; 7 8 // S e i t PHP 5 . 4 : Short a r r a y syntax 9 $ c o l o r s = [ ' red ' , ' g r e e n ' , ' y e l l o w ' ] ; 14
  • 15. Man kann sehr dynamisch und flexibel mit Arrays arbeiten 1 <?php 2 $array = array () ; 3 4 // Neue Elemente a n l e g e n 5 $array [ ] = ' eintrag 1 ' ; 6 $array [ ] = ' eintrag 2 ' ; 7 8 // Lese das e r s t e Element aus 9 $one = $ a r r a y [ 0 ] ; 10 11 // S o r t i e r e d i e Elemente im Array nach Keys 12 ksort ( $array ) ; 13 14 // E n t f e r n e e i n Element aus einem Array 15 unset ( $array [ 0 ] ) ; 15
  • 16. Funktionen 1 <?php 2 // Addiere 1 dazu 3 f u n c t i o n my_inc ( $ i n t ) { r e t u r n ++$ i n t ; } 4 // Teste d i e Funktion 5 echo my_inc ( 1 ) ; 6 // Funktion per C a l l b a c k verwenden 7 echo c a l l _ u s e r _ f u n c ( ' my_inc ' , 1) ; 8 9 // S e l b i g e s a l s Anonyme Funktion ( C l o s u r e ) 10 $my_inc = f u n c t i o n ( $ i n t ) { r e t u r n ++$ i n t ; } 11 // Teste d i e Funktion 12 echo $my_inc ( 2 ) ; 13 // Anonyme Funktion per C a l l b a c k verwenden 14 echo c a l l _ u s e r _ f u n c ( $my_inc , 2) ; 16
  • 17. Verzweigungen 1 <?php // Wenn Dann 2 i f (1 === TRUE) { echo ' 1 i s t genau TRUE' } ; 3 // A l t e r n a t i v e 4 e l s e i f (1 == TRUE) { echo ' 1 i s t sowas wie TRUE' ; } 5 // Sonst 6 e l s e { echo ' 1 i s t n i c h t TRUE' } ; Schleifen 1 <?php // For−S c h l e i f e ( e t w a i g wie i n C) 2 f o r ( $ i = 0 ; $ i < 1 0 ; $ i++) { echo $ i . ' ' ; } 3 4 // Foreach−S c h l e i f e ( s e h r g e e i g n e t b e i Arrays ) 5 f o r e a c h ( $ a r r a y AS $key => $ v a l u e ) { echo '~ ' ; } 17
  • 18. 2.3 Gefahren und Stützräder Globale Werte und Input-Daten Typ Beispiele Bemerkungen Globals $GLOBALS[’var’] Unsauber und seit 5.4 JIT Global Import global $var Etwaig wie Globals Superglobals $_GET[’id’] Nicht ungefiltert verwenden Register Globals $_GET[’id’] als $id Seit 5.4 entfernt Strings und Anführungszeichen Typ Beispiele Bemerkungen Null Byte 0 oder %00 Wirkt anders als man denkt Bearbeitung substr($var) Besser iconv_substr($var) Magic Quotes $_POST mit addslashes Seit 5.4 entfernt Encoding Byte order mark Mag PHP nicht leiden 18
  • 19. Weiteres Typ Beispiele Bemerkungen 64 bit builds amd64 Noch nicht ausgereift Threads Multi-Threading Siehe Abschnitt Installation Eval eval(’php sourcecode’) Viel Spaß beim absichern Safe Mode Künstliche Verbote Seit 5.4 entfernt Abhilfen Typ Beispiele Bemerkungen SQL Injection Quotes, Union Prepared Statements (PDO) Remote Exec include $file allow_url_include deaktivieren Headers send echo vor header Ausgabepuffer (ob_*) Erweiterung der Sicherheit: PECL taint, Suhosin Patch, open_basedir, display_errors, ... 19
  • 20. 2.4 Arbeit mit externen Daten Superglobals 1 <?php // D e t a i l s zum S e r v e r und dem Anfrage−Z i e l 2 $_SERVER 3 // HTTP GET Daten 4 $_GET 5 // HTTP POST Daten 6 $_POST 7 // M u l t i p a r t Daten 8 $_FILES 9 // Cookies s e t z e n und a b r u f e n 10 s e t c o o k i e ( ' name ' , ' i n h a l t ' ) ; 11 $_COOKIE 12 // S e s s i o n s t a r t e n und verwenden 13 session_start () 14 $_SESSION 20
  • 21. Dateisystem 1 <?php 2 // Lese den I n h a l t e i n e r Datei e i n 3 $text = file_get_contents ( ' test . txt ' ) ; 4 5 // S c h r e i b e den I n h a l t i n e i n e andere Datei 6 file_put_contents ( ' test2 . txt ' , $text ) ; 7 8 // Das Lesen geht z .B. auch per URI 9 $uri = u r l e n c o d e ( ' http : / /www. php . net / index . php ' ) ; 10 $text2 = file_get_contents ( $uri ) ; 11 /∗ 12 ∗ Man s o l l t e b e i URIs immer u r l e n c o d e verwenden 13 ∗ und vor e i n e r Ausgabe den I n h a l t a b s i c h e r n 14 ∗/ 21
  • 22. User Memory Cache (KeyValueStore) 1 <?php $ r e s u l t = ' ' ; 2 // Check a u f E x i s t e n z der Erweiterung 3 i f ( e x t e n s i o n _ l o a d e d ( ' xcache ' ) ) { 4 5 // S p e i c h e r e e i n e n E i n t r a g 30 Sekunden l a n g 6 xcache_set ( ' key ' , ' t e s t v a l u e ' , 30) ; 7 8 // Lade den E i n t r a g 9 i f ( x c a c h e _ i s s e t ( ' key ' ) ) { 10 11 $ r e s u l t = xcache_get ( ' key ' ) ; 12 } 13 } 14 15 echo ' Cache I n h a l t : ' . $ r e s u l t ; 22
  • 23. 2.5 Argumentation Vorteile - Sehr gut dokumentiert, einfach zu Lernen, schnelle Resultate - Flexibel verwendbar, Plattformunabhängig, alles Wichtige dabei - Hochgradig skalierbar, leichtes Deployment, Cloud Betrieb möglich - Direkter und vollständiger Support von HTTP und der Server-API - Durchdachte Einteilung von Sichtbarkeitsbereichen der Variablen - Keine laufende Anwendung nötig, wird gestartet und verworfen Nachteile - Schnelle Resultate führen zu Fehlern und schlechter Code Qualität - Historisch gewachsen, daher teilweise mehrere Wege für ein Ziel - PHP Erweiterungen untereinander sehr unterschiedlich aufgebaut - Strings werden nur Byte-basiert verwendet (Abhilfen vorhanden) - Fehlende Features treiben Enterprise Frameworks in Workarounds 23
  • 24. 3 Anhang 3.1 Verweise und Empfehlungen Websites zu den Themen http://www.php.net/manual PHP Manual http://pear.php.net PHP PEAR http://pecl.php.net PHP PECL http://www.hardened-php.net/suhosin Suhosin Patch http://httpd.apache.org Apache Webserver http://www.apachelounge.com Apache for Windows http://xcache.lighttpd.net XCache Extension Bücher zu den Themen Programming PHP O’Reilly Der Klassiker von Rasmus Lerdorf PHP 5 Kochbuch O’Reilly Lösungswege für gängige Aufgaben 24