Pemrograman Web PHP 1 Antonius RC 2011 Server side PHP merupakan salah bahasa pemrograman yang berjalan pada sisi server Dapat menggenerate HTML!
PHP merupakan bahasa pemrograman yang menggunakan sintaks keturunan C/C++ PHP files have a file extension of ".php", ".php3", or ".phtml" PHP singkatan dari PHP Hypertext Preprocessors www.php.net (latest stable: 5.3.8) Singkatan pertama: Personal Home Page, Professional Home Page
Web Server ApacheFriends XAMPP: Bundle: PHP, MySQL, Perl, Mail Server, FTP Server Xampp Control panel running For xampp, put php here: xampp\apache\ htdocs
PHP Usage PHP in TIOBE Index Sejarah PHP Dibuat oleh Rasmus Lerdorf (1994) PHP/FI2.0 (Personal Homepage) Versi PHP3 (1997)
Zeev Suraski and Andi Gutmans (Zend) Versi PHP4 (2000) menjadi sangat populer di web Berkembang ke OOP (Java, C#, VB.NET) Kemudian munculah PHP5 yang support OOP WEB SERVER
Gets Page HTTP Request (url)
Server response CLIENT Browser creates the web page Hello
Interprets the PHP code Hello Yang baru di PHP 5 New and improved MySQL extension (mysqli.dll)
PHP 5 bundles SQLite (sqlite.dll sqlite3.dll) Supports SimpleXML extension (XML) New Iterators and Structure Programming Language More Error Handling and Debugging Supports Streams, Filters, and Wrappers PHP 5 Architecture Zend engine as parser (Andi Gutmans and Zeev Suraski)
SAPI (Server Application Programming Interface) is a web server abstraction layer - php5apache2.dll PHP components now self contained (ODBC, Java, LDAP, etc.) This structure is a good general design for software (compare to OSI model, and middleware applications) image from http://www.zend.com/zend/art/intro.php 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. PHP Block
PHP code block is embedded within the tags. When the server encounters the PHP tags it switches from the HTML to PHP mode. There are four different ways to embed the PHP code
echo(Some PHP code); ?> <% echo(Some PHP code); %> PHP - Variables
Prefixed with a $ Assign values with = operator No need to define type Variable names are case sensitive $author and $Author are different
A variable name must start with a letter or an underscore "_" A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) A variable name should not contain spaces If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString)
PHP Data Type Three basic data types Integer Double String More data types Array Object
PHP is an untyped language variables type can change on the fly. 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 dengan: Petik ganda ( ). contoh: $a = Nama: $nama\n; Petik tunggal (' '). contoh: $b = 'c:\*.*';
Pengaksesan karakter string $a = ini test; $pertama = $a{0}; $ketiga = $a{2}; $akhir = $a{strlen($a)-1}; First PHP
Hello PHP"; echo
I love web programming; ?> 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; Contoh Tipe Data
Useful string functions str_replace()
trim(), ltrim(), rtrim() implode(), explode() addslashes(), stripslashes() htmlentities(), html_entity_decode(), htmlspecialchars() striptags() Contoh
Operator Untuk String : titik (.) Untuk Numerik : +, -, *, /, %, ++, - Untuk Boolean: &&, ||, ! Operator Perbandingan 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 $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; }
?> Switch Switch (2) Struktur While
while ($i <= 10) { echo $i++; } $i = 1; while ($i <= 10): echo $i; $i++; endwhile; ?>
=1); ?> Struktur for
Cara Looping Dapat digunakan pada array! Tanpa sebut index 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
"; } ?>
Array In PHP, there are three kind of arrays: Numeric array - An array with a numeric index $cars=array("Saab","Volvo","BMW","Toyota"); Associative array - An array where each ID key is associated with a value $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); Multidimensional array - An array containing one
or more arrays Array Associative Array Custom Array 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 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 array_flip() swaps keys for values array_count_values() returns an associative array of all values in an array, and their frequency array_rand() pulls a random element array_unique() removes duppies array_walk() applies a user defined function to each element of an array (so you can
dice all of a dataset) count() returns the number of elements in an array array_search() returns the key for the first match in an array Contoh penggunaan explode/implode Function (by value) Function definition 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) function tax(&$salary){ $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){ $salary = $salary-(($salary/100)*20); return $salary; }
echo tax(); ?> Include vs Require The include() function takes all the content in a specified file and includes it in the current file. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() function is identical to include(),
except that it handles errors differently. If an error occurs, require() generates a fatal error, and the script will stop. Contoh include Include vs Require Diganti require
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() date() dan mktime() Format: date(format,timestamp) d - Represents the day of the month (01 to 31) m - Represents a month (01 to 12) Y - Represents a year (in four digits)
Format: mktime(hour,minute,second,month,day,year,is _dst) phpinfo() The phpinfo() function shows the php environment Use this to read system and server variables, setting stored in php.ini, versions, and
modules Notice that many of these data are in arrays This is the first script you should write phpinfo() 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
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. contoh
Percobaan Login Buat 2 textbox untuk login: Username dan password Buat 1 button untuk Submit Form action=proseslogin.php Method=POST Array global pada PHP
$_GET[variabel] untuk menerima variabel pada URL secara GET $_POST[variabel] untuk menerima variabel dari POST form $_REQUEST[variabel] untuk menerima variabel GET dan POST $_FILES[variabel] untuk menerima upload file $_SESSION[varname] untuk mengakses session $_COOKIE[varname] untuk mengakses cookies
Session
session_start(); $_SESSION[] = ; session_unregister( if (isset($_SESSION[])){ } session_regenerate_id(); session_destroy() Kode Login
Home Logout NEXT PHP 2 + PHP OOP