You are here

PHP - Reference

<?
// PHP steht fuer "Hypertext Pre-Processor" und wird
// direkt mit HTML in eine Datei geschrieben
 
    // moegliche Arten PHP Code in HTML Site einzubinden:
?>
        <? ... ?>
        <?php ... ?> 
        <script language="php"> ... </script>
 
<?
    // Dateien inkludieren
        include("dateiname");
    // Namensraeume
        namespace MyProject;
        namespace MyProject\Sub\Level;
        require 'asdf.php';
        use MyProject;
        \funcName(...);     // globale Funktion aufrufen
    // Fehlermeldung ignorieren
        @ vor einen Ausdruck
 
 
    // standard Ausgabe
        echo "hello world<br>";
        echo $str;
        echo $str, "and" ,$str;
        echo "$str and $str";
        $str = <<<EOD
            Text, welcher ueber
            mehrere Zeilen geht
EOD;
 
        print "hello world\n";
        sprintf('hello world %d %s', $integer, $string);
        print_r($arr);
 
 
    // Variablen Definition
        global, static      // Geltungsbereiche
 
        $boolean = true;
        $text = "hello";
        $firstChar = $text[0];
        $integer = 12;
        $integer = 0xff;    // hexadezimal
        $integer = 0123;    // octal
        $float = 1.2;
        $float = 1.2e3;
        $float = 1E-2;
 
 
    // Konstanten
        define("NAME", "value");
        const NAME = 'value';
 
        __LINE__        // ... aktuelle Zeilennummer
        __FILE__        // ... vollstaendige Pfad- und Dateiname einer Datei
        __DIR__         // ... Name des Verzeichnisses
        __FUNCTION__    // Name der Funktion
        __CLASS__       // Name einer Klasse
        __METHOD__      // Name einer Klassenmethode
        __NAMESPACE__   // Name des aktuellen Namespace
 
 
    // global definierte Variablen
        $GLOBALS                // Referenziert alle Variablen, die im
                                // globalen Gueltigkeitsbereich vorhanden sind
        $_SERVER                // Informationen ueber Server und
                                // Ausfuehrungsumgebung
        $_GET                   // HTTP GET-Variablen
        $_POST                  // HTTP POST-Variablen
        $_FILES                 // HTTP Dateiupload-Variablen
        $_REQUEST               // HTTP Request-Variablen
        $_SESSION               // Sessionvariablen
        $_ENV                   // Umgebungsvariablen
        $_COOKIE                // HTTP Cookies
        $php_errormsg           // Die vorangegangene Fehlermeldung
        $HTTP_RAW_POST_DATA     // Raw POST-Daten
        $http_response_header   // HTTP Response-Header
        $argc                   // Die Anzahl der an das Skript
                                // übergebenen Argumente
        $argv                   // Array der an das Skript
                                // übergebenen Argumente
 
 
    // Session Variablen
        session_start();        // Session starten und Wert speichern
        session_register('variable');
        $variable = 'value';
 
        session_start();
        $_SESSION[variable]     // Wert auf weiteren Seite verwenden
 
 
    // Array Definitionen
        $arr = array("first", "second", "third");
        $arr = array('index1' => 'value1', 'index2' => 'value2');
        $arr['index1'];
 
        $arr[] = "1";
        $arr[] = "2";
        sort($arr);
        count($arr);
 
        array("somearray" => array(0 => 10, 1 => 11, "a" => 12));
        echo $arr["somearray"][0];
        echo $arr["somearray"][1];
        echo $arr["somearray"]["a"];
 
        unset($arr[0]);                         // 0-Element loeschen
        unset($arr);                            // gesamte Array loeschen
 
        foreach($arr as $key=>$value)           // Array durchlaufen
        {
            echo "arr[$key] = $value <br>";
        }
 
        $arr = array(1 => 'one', 2 => 'two', 3 => 'three');
        unset($a[2]);
        /* arr = array(1 => 'one', 3 => 'three'); */
        $brr = array_values($arr);
        /* $brr = array(0 => 'one', 1 =>'three') */
 
        $arr1 = array(2, 3);
        $arr2 = $arr1;
        $arr2[] = 4;                            // $arr2 wurde geaendert
                                                // $arr1 bleibt gleich
        $arr3 = &$arr1;
        $arr3[] = 4;                            // $arr1 und $arr3 sind
                                                // die selben
 
 
        isset($var);
 
 
    // Referenzen
        $a =& $b;                               // a ist gleich dem Objekt b
 
 
    // Casts
        (bool) 1
        (boolean) 1
        (int) 12
        (integer) 12
        (real), (double), (float)
        (string)
        (array)
        (object)
 
        gettype()
        is_bool()
        is_long()
        is_float()
        is_string()
        is_array()
        is_object()
 
 
    // Classes
        class cl
        {
            var $var;
 
            function cl()                       // C-TOR
            { }
            function __construct()
            { }
 
            function __destruct()               // D-TOR
            { }
 
            function doSmth()
            {
                $this->var = array();
            }
 
            final public function asdf()        // kann nicht
            { }                                 // ueberschrieben werden
 
            public $public = 'Public';          // Sichtbarkeit
            protected $protected = 'Protected';
            private $private = 'Private';
 
            public function asdf() {}
            protected function asdf() {}
            private function asdf() {}
        }
        $cl1 = new cl;
        $cl1->doSmth();
 
        class cl2 extends cl                    // Ableiten
        {
            function doSmth()
            {
                cl::doSmth();                   // Scope Resolution
                parent::doSmth();
                self::doSmth();
                ...
            }
        }
 
        abstract class abstrCl                  // abstrakte Klasse
        {
            // Methode welche implementiert werden muss
            abstract protected function doSmth();
 
            // Gemeinsam verfuegbare Methode
            public function doSmth2()
            { ... }
        }
 
        interface iAsdf                         // Interface
        {
            public function doSmth1($var1, $var2);
            public function doSmth2();
        }
        class asdf implements iAsdf
        { ... }
 
 
    // Serializing
        // classa.inc:
        class A
        {
            var $one = 1;
 
            function doSmth()
            { }
        }
 
        // page1.php:
        include("classa.inc");
        $a = new A;
        $s = serialize($a);
        $fp = fopen("test.dat", "w");
        fwrite($fp, $s);
        fclose($fp);
 
        // page2.php:
        include("classa.inc");
        $s = implode("", @file("test.dat"));
        $a = unserialize($s);
        $a->doSmth();
 
 
    // Formularuebergaben
        // Formular:
        //  <form action="doit.php" method="post">
        //      <input type="text" name="inputVar">
        //      <input type="submit">
        //  </form>
 
        // vorhandene Variablen
        echo $_POST['inputVar'];
        echo $_REQUEST['inputVar'];
        echo "Eingabe: $inputVar";
 
 
    // Arithmetische Operationen
        $i = $x + $y;       // Addition
        $i = $x - $y;       // Subtraktion
        $i = $x * $y;       // Multiplikation
        $i = $x / $y;       // Division
        $i = $x % $y;       // Modulo
        $i = $x . $y;       // Verbinden von Strings
        $i++;               // Post-Inkrement
        ++$i;               // Pre-Inkrement
        $i--;               // Post-Dekrement
        --$i;               // Pre-Dekrement
 
        $i += $x;
        $i -= $x;
        $i *= $x;
        $i /= $x;
 
 
    // Bit Operationen
        &                   // Und
        |                   // Oder
        ^                   // XOR
        ~                   // Negiert
        <<                  // shift left
        >>                  // shift right
 
 
    // Logische Operationen
        and
        or
        xor
        !
        &&
        ||
 
 
    // Vergleiche
        $i < $j             // kleiner
        $i > $j             // groesser
        $i <= $j            // kleiner gleich
        $i >= $j            // groesser gleich
        $i == $j            // gleich
        $i === $j           // identisch
        $i != $j            // ungleich
        $i !== $j           // nicht identisch
        $i <> $j            // ungleich
 
 
    // Kontrollstrukturen
        while ($CONDITION)
        { }
 
        do
        { }
        while ($CONDITION);
 
        for ($i=0; $i<10; $i++)
        { }
 
        foreach ($values as $value)
        { }
 
        if ($CONDITION)
        { }
        else if ($CONDITION)
        { }
        else
        { }
 
        CONDITION ? $true : $false
 
        switch ($var)
        {
            case "asdf":
                break;
            case "qwer":
                break;
            default:
        }
 
 
    // Funktionen
        function aFunc ($Var)               // call-by-value
        {
            return $Var;
        }
 
        function aFunc (&$Var)              // call-by-reference
        {
            $Var .= 'asdf';
        }
 
        function aFunc_retArr ()            // Rueckgabe eines Arrays
        {
            return array(1, 2, 3);
        }
        $res = aFunc_retArr();
        $res[0]
        $res[1]
        $res[2]
 
        function aFunc ($Var = "preinit")   // Vorinitialisierung
        function aFunc ($Var = NULL)
 
 
    // Exceptions
    try
    {
        throw new Exception('asdf');
    }
    catch (Exception $exc)
    {
        echo $e->getMessage();
    }
 
 
    // String Operationen
        $var = "asdf";
        echo "some text before $vars";      // wuerde nicht funktionieren
        echo "some text before ${var}s";    // wuerde funktionieren
        echo "some text before {$var}s";    // wuerde funktionieren
 
        strlen($str);
 
        trim(" asdf ");         // Whitespaces am Anfang und Ende entfernen
        ltrim(" asdf");         // -,,- am Anfang
        chop("asdf ");          // -,,- am Ende
 
        strtoupper("asdf");     // in Grossbuchstaben umwandeln
        strtolower("ASDF");     // in Kleinbuchstaben umwandeln
        ucfirst("asdf");        // ersten Buchstaben -> gross
        ucwords("asdf asdf");   // jeder erste Buchstabe eines Wortes -> gross
 
        nl2br("asdf\nasdf");    // new line to <br>
 
        preg_split("/-/", $str);    // String aufteilen
        implode('-', $strArray);    // String-Array zusammenfuegen
 
        // \n       linefeed
        // \r       carriage return
        // \t       horizontal tab
        // \v       vertical tab
        // \f       form feed
        // \\       backslash
        // \$       dollar sign
        // \"       double quote
 
 
    // Datei Operationen
        $datei = fopen("asdf.txt","r");
            // r  ... lesen
            // r+ ... lesen und schreiben
            // w  ... schreiben (falls existiert -> zuvor loeschen)
            // w+ ... lesen und schreiben (falls existiert -> zuvor loeschen)
            // a  ... anfuegen (Cursor befindet sich am Ende)
            // a+ ... lesen und anfuegen (Cursor befindet sich am Ende)
        feof($datei);
        $zeile = fgets($datei);
        $zeile = fgets($datei,1000);
        fwrite($datei, $str . "...");
        fclose($datei);
 
 
    // Bild Operationen
        < ?
            Header( "Content-type: image/gif");
            $img = imagecreate(200,100);
            $clr = ImageColorAllocate($img, 0x01,0x02,0x03);
            ImageFilledRectangle($img,0,0,200,100,$clr);
            Imagestring($img, 5, 20, 20, "asdf", $clr);
            ImageGif($img);
            ImageDestroy($img);
        ? >
 
 
    // Datenbank Operationen
        $connection = mysql_connect("localhost","user","pwd");
        if (!$connection)
        {
            echo "no connection!\n";
            exit;
        }
        else
        {
            $query = "SELECT col1,col2 FROM table";
            $result = mysql_db_query("www2", $query, $connection);
            list($Col1, $Col2) = mysql_fetch_row($result);
            mysql_close($connection);
        }
 
 
    // Cookie
        < ?
            $expireSec = time() + 3600*24*10;
            setcookie("Name", "Value", $expireSec, "/");
            SetCookie("Name", "Value", $expireSec, "/path",".domain");
        ? >
        <HTML>
 
        $_COOKIE["Name"]                // auf vorhandene Cookies zugreifen
        $expireSec = time() - 3600;     // Cookie loeschen
        setcookie("Name", "", $expireSec, "/path");
 
?>