1<?
2// PHP steht fuer "Hypertext Pre-Processor" und wird
3// direkt mit HTML in eine Datei geschrieben
4
5 // moegliche Arten PHP Code in HTML Site einzubinden:
6?>
7 <? ... ?>
8 <?php ... ?>
9 <script language="php"> ... </script>
10
11<?
12 // Dateien inkludieren
13 include("dateiname");
14 // Namensraeume
15 namespace MyProject;
16 namespace MyProject\Sub\Level;
17 require 'asdf.php';
18 use MyProject;
19 \funcName(...); // globale Funktion aufrufen
20 // Fehlermeldung ignorieren
21 @ vor einen Ausdruck
22
23
24 // standard Ausgabe
25 echo "hello world<br>";
26 echo $str;
27 echo $str, "and" ,$str;
28 echo "$str and $str";
29 $str = <<<EOD
30 Text, welcher ueber
31 mehrere Zeilen geht
32EOD;
33
34 print "hello world\n";
35 sprintf('hello world %d %s', $integer, $string);
36 print_r($arr);
37
38
39 // Variablen Definition
40 global, static // Geltungsbereiche
41
42 $boolean = true;
43 $text = "hello";
44 $firstChar = $text[0];
45 $integer = 12;
46 $integer = 0xff; // hexadezimal
47 $integer = 0123; // octal
48 $float = 1.2;
49 $float = 1.2e3;
50 $float = 1E-2;
51
52
53 // Konstanten
54 define("NAME", "value");
55 const NAME = 'value';
56
57 __LINE__ // ... aktuelle Zeilennummer
58 __FILE__ // ... vollstaendige Pfad- und Dateiname einer Datei
59 __DIR__ // ... Name des Verzeichnisses
60 __FUNCTION__ // Name der Funktion
61 __CLASS__ // Name einer Klasse
62 __METHOD__ // Name einer Klassenmethode
63 __NAMESPACE__ // Name des aktuellen Namespace
64
65
66 // global definierte Variablen
67 $GLOBALS // Referenziert alle Variablen, die im
68 // globalen Gueltigkeitsbereich vorhanden sind
69 $_SERVER // Informationen ueber Server und
70 // Ausfuehrungsumgebung
71 $_GET // HTTP GET-Variablen
72 $_POST // HTTP POST-Variablen
73 $_FILES // HTTP Dateiupload-Variablen
74 $_REQUEST // HTTP Request-Variablen
75 $_SESSION // Sessionvariablen
76 $_ENV // Umgebungsvariablen
77 $_COOKIE // HTTP Cookies
78 $php_errormsg // Die vorangegangene Fehlermeldung
79 $HTTP_RAW_POST_DATA // Raw POST-Daten
80 $http_response_header // HTTP Response-Header
81 $argc // Die Anzahl der an das Skript
82 // uebergebenen Argumente
83 $argv // Array der an das Skript
84 // uebergebenen Argumente
85
86
87 // Session Variablen
88 session_start(); // Session starten und Wert speichern
89 session_register('variable');
90 $variable = 'value';
91
92 session_start();
93 $_SESSION[variable] // Wert auf weiteren Seite verwenden
94
95
96 // Array Definitionen
97 $arr = array("first", "second", "third");
98 $arr = array('index1' => 'value1', 'index2' => 'value2');
99 $arr['index1'];
100
101 $arr[] = "1";
102 $arr[] = "2";
103 sort($arr);
104 count($arr);
105
106 array("somearray" => array(0 => 10, 1 => 11, "a" => 12));
107 echo $arr["somearray"][0];
108 echo $arr["somearray"][1];
109 echo $arr["somearray"]["a"];
110
111 unset($arr[0]); // 0-Element loeschen
112 unset($arr); // gesamte Array loeschen
113
114 foreach($arr as $key=>$value) // Array durchlaufen
115 {
116 echo "arr[$key] = $value <br>";
117 }
118
119 $arr = array(1 => 'one', 2 => 'two', 3 => 'three');
120 unset($a[2]);
121 /* arr = array(1 => 'one', 3 => 'three'); */
122 $brr = array_values($arr);
123 /* $brr = array(0 => 'one', 1 =>'three') */
124
125 $arr1 = array(2, 3);
126 $arr2 = $arr1;
127 $arr2[] = 4; // $arr2 wurde geaendert
128 // $arr1 bleibt gleich
129 $arr3 = &$arr1;
130 $arr3[] = 4; // $arr1 und $arr3 sind
131 // die selben
132
133
134 isset($var);
135
136
137 // Referenzen
138 $a =& $b; // a ist gleich dem Objekt b
139
140
141 // Casts
142 (bool) 1
143 (boolean) 1
144 (int) 12
145 (integer) 12
146 (real), (double), (float)
147 (string)
148 (array)
149 (object)
150
151 gettype()
152 is_bool()
153 is_long()
154 is_float()
155 is_string()
156 is_array()
157 is_object()
158
159
160 // Classes
161 class cl
162 {
163 var $var;
164
165 function cl() // C-TOR
166 { }
167 function __construct()
168 { }
169
170 function __destruct() // D-TOR
171 { }
172
173 function doSmth()
174 {
175 $this->var = array();
176 }
177
178 final public function asdf() // kann nicht
179 { } // ueberschrieben werden
180
181 public $public = 'Public'; // Sichtbarkeit
182 protected $protected = 'Protected';
183 private $private = 'Private';
184
185 public function asdf() {}
186 protected function asdf() {}
187 private function asdf() {}
188 }
189 $cl1 = new cl;
190 $cl1->doSmth();
191
192 class cl2 extends cl // Ableiten
193 {
194 function doSmth()
195 {
196 cl::doSmth(); // Scope Resolution
197 parent::doSmth();
198 self::doSmth();
199 ...
200 }
201 }
202
203 abstract class abstrCl // abstrakte Klasse
204 {
205 // Methode welche implementiert werden muss
206 abstract protected function doSmth();
207
208 // Gemeinsam verfuegbare Methode
209 public function doSmth2()
210 { ... }
211 }
212
213 interface iAsdf // Interface
214 {
215 public function doSmth1($var1, $var2);
216 public function doSmth2();
217 }
218 class asdf implements iAsdf
219 { ... }
220
221
222 // Serializing
223 // classa.inc:
224 class A
225 {
226 var $one = 1;
227
228 function doSmth()
229 { }
230 }
231
232 // page1.php:
233 include("classa.inc");
234 $a = new A;
235 $s = serialize($a);
236 $fp = fopen("test.dat", "w");
237 fwrite($fp, $s);
238 fclose($fp);
239
240 // page2.php:
241 include("classa.inc");
242 $s = implode("", @file("test.dat"));
243 $a = unserialize($s);
244 $a->doSmth();
245
246
247 // Formularuebergaben
248 // Formular:
249 // <form action="doit.php" method="post">
250 // <input type="text" name="inputVar">
251 // <input type="submit">
252 // </form>
253
254 // vorhandene Variablen
255 echo $_POST['inputVar'];
256 echo $_REQUEST['inputVar'];
257 echo "Eingabe: $inputVar";
258
259
260 // Arithmetische Operationen
261 $i = $x + $y; // Addition
262 $i = $x - $y; // Subtraktion
263 $i = $x * $y; // Multiplikation
264 $i = $x / $y; // Division
265 $i = $x % $y; // Modulo
266 $i = $x . $y; // Verbinden von Strings
267 $i++; // Post-Inkrement
268 ++$i; // Pre-Inkrement
269 $i--; // Post-Dekrement
270 --$i; // Pre-Dekrement
271
272 $i += $x;
273 $i -= $x;
274 $i *= $x;
275 $i /= $x;
276
277
278 // Bit Operationen
279 & // Und
280 | // Oder
281 ^ // XOR
282 ~ // Negiert
283 << // shift left
284 >> // shift right
285
286
287 // Logische Operationen
288 and
289 or
290 xor
291 !
292 &&
293 ||
294
295
296 // Vergleiche
297 $i < $j // kleiner
298 $i > $j // groesser
299 $i <= $j // kleiner gleich
300 $i >= $j // groesser gleich
301 $i == $j // gleich
302 $i === $j // identisch
303 $i != $j // ungleich
304 $i !== $j // nicht identisch
305 $i <> $j // ungleich
306
307
308 // Kontrollstrukturen
309 while ($CONDITION)
310 { }
311
312 do
313 { }
314 while ($CONDITION);
315
316 for ($i=0; $i<10; $i++)
317 { }
318
319 foreach ($values as $value)
320 { }
321
322 if ($CONDITION)
323 { }
324 else if ($CONDITION)
325 { }
326 else
327 { }
328
329 CONDITION ? $true : $false
330
331 switch ($var)
332 {
333 case "asdf":
334 break;
335 case "qwer":
336 break;
337 default:
338 }
339
340
341 // Funktionen
342 function aFunc ($Var) // call-by-value
343 {
344 return $Var;
345 }
346
347 function aFunc (&$Var) // call-by-reference
348 {
349 $Var .= 'asdf';
350 }
351
352 function aFunc_retArr () // Rueckgabe eines Arrays
353 {
354 return array(1, 2, 3);
355 }
356 $res = aFunc_retArr();
357 $res[0]
358 $res[1]
359 $res[2]
360
361 function aFunc ($Var = "preinit") // Vorinitialisierung
362 function aFunc ($Var = NULL)
363
364
365 // Exceptions
366 try
367 {
368 throw new Exception('asdf');
369 }
370 catch (Exception $exc)
371 {
372 echo $e->getMessage();
373 }
374
375
376 // String Operationen
377 $var = "asdf";
378 echo "some text before $vars"; // wuerde nicht funktionieren
379 echo "some text before ${var}s"; // wuerde funktionieren
380 echo "some text before {$var}s"; // wuerde funktionieren
381
382 strlen($str);
383
384 trim(" asdf "); // Whitespaces am Anfang und Ende entfernen
385 ltrim(" asdf"); // -,,- am Anfang
386 chop("asdf "); // -,,- am Ende
387
388 strtoupper("asdf"); // in Grossbuchstaben umwandeln
389 strtolower("ASDF"); // in Kleinbuchstaben umwandeln
390 ucfirst("asdf"); // ersten Buchstaben -> gross
391 ucwords("asdf asdf"); // jeder erste Buchstabe eines Wortes -> gross
392
393 nl2br("asdf\nasdf"); // new line to <br>
394
395 preg_split("/-/", $str); // String aufteilen
396 implode('-', $strArray); // String-Array zusammenfuegen
397
398 // \n linefeed
399 // \r carriage return
400 // \t horizontal tab
401 // \v vertical tab
402 // \f form feed
403 // \\ backslash
404 // \$ dollar sign
405 // \" double quote
406
407
408 // Datei Operationen
409 $datei = fopen("asdf.txt","r");
410 // r ... lesen
411 // r+ ... lesen und schreiben
412 // w ... schreiben (falls existiert -> zuvor loeschen)
413 // w+ ... lesen und schreiben (falls existiert -> zuvor loeschen)
414 // a ... anfuegen (Cursor befindet sich am Ende)
415 // a+ ... lesen und anfuegen (Cursor befindet sich am Ende)
416 feof($datei);
417 $zeile = fgets($datei);
418 $zeile = fgets($datei,1000);
419 fwrite($datei, $str . "...");
420 fclose($datei);
421
422
423 // Bild Operationen
424 < ?
425 Header( "Content-type: image/gif");
426 $img = imagecreate(200,100);
427 $clr = ImageColorAllocate($img, 0x01,0x02,0x03);
428 ImageFilledRectangle($img,0,0,200,100,$clr);
429 Imagestring($img, 5, 20, 20, "asdf", $clr);
430 ImageGif($img);
431 ImageDestroy($img);
432 ? >
433
434
435 // Datenbank Operationen
436 $connection = mysql_connect("localhost","user","pwd");
437 if (!$connection)
438 {
439 echo "no connection!\n";
440 exit;
441 }
442 else
443 {
444 $query = "SELECT col1,col2 FROM table";
445 $result = mysql_db_query("www2", $query, $connection);
446 list($Col1, $Col2) = mysql_fetch_row($result);
447 mysql_close($connection);
448 }
449
450
451 // Cookie
452 < ?
453 $expireSec = time() + 3600*24*10;
454 setcookie("Name", "Value", $expireSec, "/");
455 SetCookie("Name", "Value", $expireSec, "/path",".domain");
456 ? >
457 <HTML>
458
459 $_COOKIE["Name"] // auf vorhandene Cookies zugreifen
460 $expireSec = time() - 3600; // Cookie loeschen
461 setcookie("Name", "", $expireSec, "/path");
462
463?>