Pemrograman Internet Mobile 7 PHP: Hypertext Preprocessors
PHP PHP (PHP: Hypertext Preprocessor) dikembangkan oleh Rasmus Lerdorf (1994), sebagai awal pengembangan untuk HTTP usage logging dan server- side form generation pada Unix. PHP 2 (1995) diubah menjadi bahasa Server-side embedded scripting. –Ditambahkan kemampuan database support, file uploads, variabel, array, rekursif, kondisi, iteration, regular expressions, dll.
Sejarah PHP PHP 3 (1998) ditambah dukungan untuk ODBC, multiple platform support, protokol (SNMP,IMAP), dan parser baru oleh Zeev Suraski and Andi Gutmans. PHP 4 (2000) menjadi komponen independen dari web server agar lebih efisien. Parser diganti nama menjadi Zend Engine. –Latest stable: ( PHP 5 (2004) ditambahkan Zend Engine II dengan OOP, dukungan XML dengan pustaka libxml2, SOAP untuk Web Services, SQLite telah ditambahkan dalam PHP –Versi terbaru (
Sejarah PHP Pada August 2004, PHP digunakan pada 16,946,328 domains, 1,348,793 alamat IP ( Hampir 32% dari seluruh domain web.
Mengapa PHP digunakan? Bahasa mirip C dan Java Mudah Pemakaiannya –Kode “ditanamkan” pada HTML/WML/XHTML. –Kode php dimulai dan diakhiri dengan tanda (tag) Example <?php echo "Hi, I'm a PHP script!"; ?>
Why PHP? Cross Platform –Dapat jalan hampir di semua web server pada beberapa sistem operasi –Web server: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server –Sistem operasi: NIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003 –Database: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm Keuntungan dalam biaya –PHP is free.
Dukungan PHP GD (GIF, JPEG, PNG) SNMP IMAP (POP, NNTP) FTP XML parser PDF generation DCOM (Win32 only) SWF (Flash) zlib (compressed IO) Charset/text conversion (UTF-8, Cyrillic, Hebrew) SOAP Cybercash ASPELL/PSPELL
PHP Model Source: <?php echo(“Hello World!”); ?> Menjadi: Hello World!
Notasi PHP
Tipe data Scalar types –Boolean –Integer –Float –String Compound types –Array –Object Diawali dgn tanda $
Konstanta <? define(“USERNAME”,”Anton”); echo “User Name :”.USERNAME; ?>
Boolean Untuk literal boolean: true atau false Berikut dianggap bernilai false, jika –Nilai boolean FALSE –Nilai integer 0 atau float 0.0 –String yang kosong, atau string “0” –Array dengan elemen kosong –NULL (termasuk unset variabel)
Contoh Integer Nilai literal integer yang valid: –$a = 1234; –$a = -123; –$a = 0123; #octal number –$a = 0x123; #hexa number Jika nilai literal integer melebihi range Integer, otomatis PHP akan mengkonversi ke tipe float Konversi ke Integer: –Nilai boolean FALSE => 0, TRUE => 1 –Casting (int). Contoh: $a = (int) (25/7); # int(3) $a = round(25/7); # float(4)
Float Ukuran float tergantung pada platform, walaupun maksimum ~1.8e208 (64 bit format IEEE) –$a = 1.234; –$b = 1.2e4; –$c = 7E-10;
String Literal string dideklarasikan baik dengan –Petik ganda (“ “). contoh: $a = “Nama: $nama\n”; –Petik tunggal (' '). contoh: $b = 'c:\*.*'; –Heredoc. Contoh: $c = <<<EOD Ini testing EOD; Pengaksesan karakter string –$a = “ini test”; –$pertama = $a{0}; –$ketiga = $a{2}; –$akhir = $a{strlen($a)-1};
Konversi String ke Angka Contoh: –$a = 1 + “10.5”; –$a = 1 + “-1.3e3”; –$a = 1 + “bob-1.3e3”; –$a = 1 + “bob3”; –$a = 1 + “10 ayam kate”; –$a = 1 + “10.2 ayam kate”; –$a = “10.0 ayam” + 1;
Tipe Data <? $testing = 5; //integer echo gettype($testing); $testing = "five"; //string echo gettype($testing); $testing = 5.0; //double echo gettype($testing); $testing = true; //boolean echo gettype($testing); ?> <? $varumum = 3.14; $vardouble = (double)$varumum; echo gettype($vardouble); //double $varstring = (string)$varumum; echo gettype($varstring); //string ?>
array
Custom Array Contoh pembuatan array dengan custom key <?php // This array is the same as... array(5 => 43, 32, 56, "b" => 12); //...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?> Size of array is not defined If you add a new element the maximum of the integer indices is taken, and the new key will be that maximum value + 1
Array Multidimensi
Fungsi-fungsi ttg Array Implode() -> menggabungkan array menjadi string explode() -> memecah string menjadi array sort() -> mengurutkan array scr asc rsort() -> mengurutkan array scr desc ksort() -> mengurutkan index string array scr asc array_pop() -> menghapus array dr urutan terakhir array_push() -> menambah array
Contoh penggunaan fungsi <? //explodeimplode.php $city[0]="Jogja"; $city[1]="Bandung"; $city[3]="Surabaya"; $strgabung = implode("-",$city); echo "Stlh digabung: ".$strgabung." "; $cityarray = explode("-",$strgabung); foreach ($cityarray as $key=>$value){ echo "Array ke-".$key." = ".$value." "; } ?>
NULL NULL menyatakan variabel yang tidak ada nilainya Sebuah variabel NULL, jika –Dinyatakan sebagai NULL dengan opertor = –Belum pernah diberikan suatu nilai literal –Telah di unset() Untuk mengecek apakah variabel NULL atau tidak, dapat digunakan fungsi is_null()
Konvensi PHP Aturan nama variabel PHP mengikuti konvensi seperti bahasa pemrograman lainnya Untuk membuat referensi ke variabel lain $a = “test”; $b = &$a; # referensi $b = “ayam”; echo ($a. ' == '. $b); Variabel dari variabel $a = “hello”; $$a = “world”; echo “$a ${$a}”; echo “$a $hello”;
Unset dan Bracket
Ruang Lingkup Contoh berikut, variabel $a dapat diakses dari dalam file include atau require <?php $a = 1; include "b.inc"; ?> Variabel bersifat lokal dalam suatu fungsi <?php $a = 1; /* global scope */ function Test() { echo $a; /* menunjuk ke lokal variabel */ } Test(); ?>
Operator Aritmatika Assignment
Operator Perbandingan
Ternary operator <?php // Contoh Ternary Operator $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; // sama dengan if/else berikut: if (empty($_POST['action'])) { $action = 'default'; } else { $action = $_POST['action']; } ?>
Perbandingan <?php if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?>
<? $mood = "sad"; switch($mood){ case "happy": echo "Mood anda bagus !"; break; case "sad": echo "Mood anda sedang jelek..."; break; default: echo "Mood anda $mood"; } ?>
Struktur While <?php $i = 1; while ($i <= 10) { echo $i++; } $i = 1; while ($i <= 10): echo $i; $i++; endwhile; ?> <?php $i = 10; do{ echo $i; }while($i>=1); ?>
Struktur for
Foreach (1) <?php $arr = array("one", "two", "three"); reset($arr); while (list($key, $value) = each ($arr)) { echo "Key: $key; Value: $value \n"; } foreach ($arr as $key => $value) { echo "Key: $key; Value: $value \n"; } ?>
Foreach (2) <?php $arr = array("one", "two", "three"); reset ($arr); while (list(, $value) = each ($arr)) { echo "Value: $value \n"; } foreach ($arr as $value) { echo "Value: $value \n"; } ?>
Switch
Switch (2)
Break <? $counter=1; while($counter<10){ if($counter==5){ echo "berhenti jika counter bernilai 5 "; break; } echo $counter." "; $counter++; } ?>
Continue <? for($counter=1;$counter<=10;$counter++){ if($counter==5) continue; echo "counter bernilai: $counter "; } ?>
Session session_start() //dipaling atas session_register( ) session_unregister( if (session_is_registered( )) unset( ) session_destroy()
File upload If(copy(source, destination))
Function (by value) New function function my_function() { echo 'My function was called'; } function fungsi_return($a,$b){ return a + b; } Calling function my_function(); $c = fungsi_return(1,2);
Function By Reference <? //functionbyreference.php function tax(&$salary){ //definisi $salary = $salary-(($salary/100)*20); return $salary; } $salary = 2000; echo tax($salary); //hasil 1600 echo $salary; //hasil 1600 ?>
Parameter default function <? function tax($salary=2000){ //definisi $salary = $salary-(($salary/100)*20); return $salary; } echo tax(); ?>
Nested function
Koneksi Database MySQL mysql_connect(,, mysql_select_db( ) mysql_query( ) mysql_fetch_array( ) mysql_close()
SERVER variable $_SERVER is an array containing information such as –Headers –Paths –Script locations The entries in this array are created by the webserver. There is no guarantee that every webserver will provide any of these; servers may omit some, or provide others
contoh
Server Variable 'argv' –Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. 'argc' –Contains the number of command line parameters passed to the script (if run on the command line).
SERVER variable 'REMOTE_ADDR' –The IP address from which the user is viewing the current page. 'REMOTE_HOST' –The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user. 'REMOTE_PORT' –The port being used on the user's machine to communicate with the web server. $_COOKIE –An associative array of variables passed to the current script via HTTP cookies. Automatically global in any scope. $_POST –An associative array of variables passed to the current script via the HTTP POST method.
NEXT