• Tidak ada hasil yang ditemukan

Membuat Web Service sederhana menggunakan PHP

N/A
N/A
argow tester email

Academic year: 2023

Membagikan " Membuat Web Service sederhana menggunakan PHP"

Copied!
18
0
0

Teks penuh

(1)

Membuat Web Service sederhana menggunakan PHP

in JSON

Web Service?? apa itu web service, wikipedia

web service adalah metode berkomunikasi antara dua elektronik device yang berjalan di atas World Wide Web. Atau dengan kata lain Web Service adalah fasilitas yang disediakan suatu website yang berupa layanan yang dapat diakses oleh sistem lain.

Contoh kasus:

Misal saya ingin membuat aplikasi android yang menggunakan data dinamis, sedangkan data itu terdapat di suatu web site tertentu. Untuk menggunakan data tersebut tentunya kita dapat melakukan strategi insert secara manual terhadap sistem database lokal pada android, tapi hal ini akan menjadi sangat merepotkan bagi developer maupun end user nantinya.

Solusi yang paling efisien adalah membuat suatu API web service yang memungkinkan aplikasi android itu dapat mengakses data dari halaman website tersebut. Dengan menggunakan solusi ini maka sewaktu- waktu ketika data yang ada di web site berubah maka secara otomatis data yang terdapat pada aplikasi android pun ikut berubah tanpa harus melakukan updating database sistem lokal android.

web service sederhana menggunakan bahasa pemrograman PHP yang akan menghasilkan return berformat JSON.

01 CREATE TABLE IF NOT EXISTS `toilet` (

02 `toilet_id` bigint(20) NOT NULL AUTO_INCREMENT, 03 `name` text NOT NULL,

04 `type` text,

05 `price` bigint(20) DEFAULT NULL, 06 `from` varchar(4) NOT NULL, 07 `to` varchar(4) NOT NULL, 08 `currency` text,

09 `lamp` int(11) NOT NULL, 10 `soap` int(11) NOT NULL,

11 `hands_dryer` int(11) NOT NULL, 12 `water` int(11) NOT NULL,

13 `tissue` int(11) NOT NULL, 14 `rate` int(11) NOT NULL,

15 `voters_number` int(11) NOT NULL, 16 `latitude` varchar(30) NOT NULL, 17 `longitude` varchar(30) NOT NULL, 18 `uid` int(10) NOT NULL,

19 KEY `toilet_id` (`toilet_id`)

20 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12

(2)

<?php

$server = "isi dengan server anda, gunakan localhost jika menggunakan xampp/wamp/lamp, dll";

$username = "isi username ke sql anda";

$password = "isi password ke sql anda";

$database = "nama database";

$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());

mysql_select_db($database, $con);

$sql = "SELECT * FROM toilet";

$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)) { $records[] = $row;

}

mysql_close($con);

$data = "{\"toilets\" : ".json_encode($records)."}";

echo $data;

?>

;

 variabel $server, $username, $password, dan $database digunakan untuk konfigurasi dalam melakukan koneksi ke database server kita.

$con digunakan untuk koneksi ke database kita.

$sql merupakan perintah SQL, SELECT * FROM toilet berarti menampilkan semua data dari tabel toilet.

$result adalah eksekusi perintah SQL atau SQL querry

$records merupakan suatu array yang nanti akan digunakan untuk menyimpan nilai dari hasil SQL querry

 pada kode diatas juga terdapat statement while yang berfungsi untuk menyimpan hasil querry kedalam array $records[].

$data digunakan untuk membuat struktur JSON, json_encode digunakan untuk melakukan generate format JSON terhadap array $records.

echo $data digunakan untuk menampilkan output JSON sehingga akhirnya data yang ada bisa diakses oleh sistem lain.

coba jalankan kode PHP yang kita buat, jika benar maka akan menghasilkan output JSON seperti berikut

(3)
(4)

{"toilets" : [

{ "toilet_id":"12","name":"Alkohol

70%","type":"2","price":"3000","dari":"00:0","ke":"00:0","currency":"2","lamp":"0","soap":"0","hands_dryer":"0","water":"0","tissue":"0","rate":"0","voters_number":"0","latitude":"- 6.233256","longitude":"106.86929","uid":"0"

} , {

"toilet_id":"13",

"name":"alkohol",

"type":"1",

"price":"2500",

"dari":"00:0",

"ke":"00:0",

"currency":"1",

"lamp":"0",

"soap":"0",

"hands _ dryer": "0",

"water":"0",

"tissue":"0",

"rate":"0",

"voters _ number": "0",

"latitude":"0",

"longitude":"0",

{"toilets" :

[{"toilet_id":"2","name":"alcohol","type":"2","price":"3000","from":"00:0","to":"00:0","currency":"2","lamp":"0","soap":"0","hands_dryer":"0","water":"0","tissue":"0","rate":"0","voters_number":"0","latitud e":"-6.233256","longitude":"106.86929","uid":"0"},

{"toilet_id":"3","name":"alcohol","type":"1","price":"2500","from":"00:0","to":"00:0","currency":"1","lamp":"1","soap":"1","hands_dryer":"1","water":"1","tissue":"1","rate":"1","voters_number":"1","latitude

":"-6.233256","longitude":"106.8684768","uid":"1"},

{"toilet_id":"4","name":"statistik","type":"1","price":"10000","from":"00:0","to":"00:0","currency":"1","lamp":"1","soap":"1","hands_dryer":"1","water":"1","tissue":"1","rate":"1","voters_number":"1","latit ude":"-6.231326","longitude":"106.865492","uid":"1"},

{"toilet_id":"5","name":"toi2","type":"1","price":"2000","from":"00:0","to":"00:0","currency":"1","lamp":"1","soap":"1","hands_dryer":"1","water":"1","tissue":"1","rate":"1","voters_number":"1","latitude":"

-6.230462","longitude":"106.869194","uid":"1"},

{"toilet_id":"6","name":"toilight","type":"3","price":"3000","from":"00:0","to":"00:0","currency":"2","lamp":"1","soap":"1","hands_dryer":"1","water":"1","tissue":"1","rate":"1","voters_number":"1","latitud e":"-6.230974","longitude":"106.867634","uid":"1"},{"toilet_id":"7","name":"Fahmi","type":"4

","price":"500","from":"00:0","to":"00:0","currency":"1","lamp":"0","soap":"0","hands_dryer":"0","water":"0","tissue":"0","rate":"1","voters_number":"2","latitude":"- 6.23743681","longitude":"106.8680155","uid":"1"},{"toilet_id":"8","name":"Bos

Bayu","type":"1","price":"3000","from":"00:0","to":"00:0","currency":"1","lamp":"0","soap":"1","hands_dryer":"1","water":"0","tissue":"1","rate":"1","voters_number":"1","latitude":"- 6.2322641121184095","longitude":"106.86707675457001","uid":"1"},{"toilet_id":"9","name":"Nefriana

Lab","type":"3","price":"100","from":"00:0","to":"00:0","currency":"1","lamp":"0","soap":"0","hands_dryer":"0","water":"0","tissue":"0","rate":"0","voters_number":"0","latitude":"- 6.23495179","longitude":"106.8702793","uid":"1"},{"toilet_id":"10","name":"Sedap

Baunya","type":"1","price":"1000","from":"00:0","to":"00:0","currency":"1","lamp":"1","soap":"1","hands_dryer":"0","water":"1","tissue":"1","rate":"1","voters_number":"1","latitude":"- 6.23186415","longitude":"106.8664893","uid":"1"},{"toilet_id":"8","name":"Bos

Bayu","type":"1","price":"3000","from":"00:0","to":"00:0","currency":"1","lamp":"0","soap":"1","hands_dryer":"1","water":"0","tissue":"1","rate":"1","voters_number":"1","latitude":"- 6.23226411","longitude":"106.8678760","uid":"1"},{"toilet_id":"8","name":"Bos

Bayu","type":"1","price":"3000","from":"00:0","to":"00:0","currency":"1","lamp":"0","soap":"1","hands_dryer":"1","water":"0","tissue":"1","rate":"1","voters_number":"1","latitude":"- 6.2322641121184095","longitude":"106.86707675457001","uid":"1"},{"toilet_id":"9","name":"Nefriana

Lab","type":"3","price":"100","from":"00:0","to":"00:0","currency":"1","lamp":"0","soap":"0","hands_dryer":"0","water":"0","tissue":"0","rate":"0","voters_number":"0","latitude":"- 6.230498980727043","longitude":"106.86640620231628","uid":"1"},{"toilet_id":"7","name":"Fahmi","type":"4

","price":"500","from":"00:0","to":"00:0","currency":"1","lamp":"0","soap":"0","hands_dryer":"0","water":"0","tissue":"0","rate":"1","voters_number":"2","latitude":"- 6.232328104685706","longitude":"106.8676346540451","uid":"1"},{"toilet_id":"10","name":"Sedap

Baunya","type":"1","price":"1000","from":"00:0","to":"00:0","currency":"1","lamp":"1","soap":"1","hands_dryer":"0","water":"1","tissue":"1","rate":"1","voters_number":"1","latitude":"- 6.231368215356651","longitude":"106.86980187892914","uid":"1"},{"toilet_id":"10","name":"Sedap

","type":"2","price":"1000","from":"00:0","to":"00:0","currency":"1","lamp":"1","soap":"1","hands_dryer":"0","water":"1","tissue":"1","rate":"1","voters_number":"1","latitude":"- 6.23059","longitude":"106.866737","uid":"1"},{"toilet_id":"11","name":"mercu buana

yogyakarta","type":"1","price":null,"from":"00.0","to":"00.0","currency":null,"lamp":"1","soap":"1","hands_dryer":"1","water":"1","tissue":"1","rate":"1","voters_number":"1","latitude":"- 7.808495","longitude":"110.270643","uid":"0"}]}

(5)

"uid":"0"

}

]

};

(6)

By David Walsh on May 6, 2009

Web services are taking over the world. I credit Twitter's epic rise to the availability of a simple but rich API. Why not use the same model for your own sites? Here's how to create a basic web service that provides an XML or JSON response using some PHP and MySQL.

With the number of persons hitting your web service (hopefully), you'll need to do adequate validation before attempting to connect to the database to avoid injection attacks. Once we get the desired results from the database, we cycle through the results to populate our return results array. Depending upon the response type desired, we output the proper header and content in the desired format.

Creating a basic web service is very simple and encourages your users to spread the word about your website or service. Want more traffic? Want your website to grow without you putting in all the effort? Create a web service!

/* require the user as the parameter */

if(isset($_GET['user']) && intval($_GET['user'])) { /* soak in the passed variable or set our own */

$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default

$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default

$user_id = intval($_GET['user']); //no default /* connect to the db */

$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB');

mysql_select_db('db_name',$link) or die('Cannot select the DB');

/* grab the posts from the db */

$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";

$result = mysql_query($query,$link) or die('Errant query: '.$query);

/* create one master array of the records */

$posts = array();

if(mysql_num_rows($result)) {

while($post = mysql_fetch_assoc($result)) {

$posts[] = array('post'=>$post);

} }

/* output in necessary format */

if($format == 'json') {

header('Content-type: application/json');

echo json_encode(array('posts'=>$posts));

} else {

header('Content-type: text/xml');

echo '<posts>';

foreach($posts as $index => $post) { if(is_array($post)) {

foreach($post as $key => $value) { echo '<',$key,'>';

if(is_array($value)) {

foreach($value as $tag => $val) {

echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';

} }

echo '</',$key,'>';

} }

}

echo '</posts>';

}

(7)

/* disconnect from the db */

@mysql_close($link);

}

http://mydomain.com/web-service.php?user=2&num=10

http://mydomain.com/web-service.php?user=2&num=10&format=json

{"posts":[{"post":{"post_title":"SSLmatic SSL Certificate Giveaway Winners","guid":"http:\/\/davidwalsh.name\/?p=2304"}},{"post":{"post_title":"MooTools

FileManager","guid":"http:\/\/davidwalsh.name\/?p=2288"}},{"post":{"post_title":"PHPTVDB: Using PHP to Retrieve TV Show Information","guid":"http:\/\/davidwalsh.name\/?

p=2266"}},{"post":{"post_title":"David Walsh: The Lost MooTools Plugins","guid":"http:\/\/davidwalsh.name\/?p=2258"}},{"post":{"post_title":"Create Short URLs Using U.Nu","guid":"http:\/\/davidwalsh.name\/?p=2218"}},{"post":{"post_title":"Create Bit.ly Short URLs Using PHP","guid":"http:\/\/davidwalsh.name\/?p=2194"}},{"post":

{"post_title":"Represent Your Repositories Using the GitHub Badge!","guid":"http:\/\/davidwalsh.name\/?p=2178"}},{"post":

{"post_title":"ZebraTable","guid":"http:\/\/davidwalsh.name\/?page_id=2172"}},{"post":{"post_title":"MooTools Zebra Table Plugin","guid":"http:\/\/davidwalsh.name\/?

p=2168"}},{"post":{"post_title":"SSLmatic: Quality, Cheap SSL Certificates and Giveaway!","guid":"http:\/\/davidwalsh.name\/?p=2158"}}]}

(8)

JSON(JavaScript Object Notation) : text based open standard designed for human readable data interchange.

Format ringkas pertukaran data computer, format JSON sering digunakan untuk mentransmisikan data terstrukutur melalui suatu koneksi jaringan pada suatu proses yang disebut serialisasi.(Wikipedia)

Format pertukaran data yang ringan, mudah dibaca dan ditulis oleh manusia, penulisan nya singkat karena menggunakn notasi-notasi yang digunakan dalam javascript seperti kurung siku [ ] dan kurung kurawal { }.

Contoh penulisan JSON

{

"namaDepan": "Budi", "namaBelakang": "Subudi", "alamat": {

"namaJalan": "Jl. Sudirman 15A", "kota": "Jakarta Selatan",

"provinsi": "DKI Jakarta", "kodePos": 11111

},

"nomerTelepon": [ "021 555-1234", "021 555-4567"

] }

Sebelum JSON digunakan untuk pertukaran data antar web, XML lah yang digunakan sebagai format pertukaran data yang ada. Tetapi dibandingkan dengan XML, JSON memiliki ukuran file yang lebih kecil karena format penulisan nya

yang lebih sederhana. JSON sebenarnya adalah subset dari javascript karena ada struktur objek dan array, sehingga dapat kita katakana bahwa JSON mendukung untuk tipe data objek yang tidak didukung oleh format xml.

(9)

MySQL atau MySQLi ?

08.30.2013

MySQL sudah sampai pada php versi 5.5.0, sudah usang dan ke depannya akan dihapus dari internal command php. Jadi bagi anda yang scriptnya coding manual menggunakan database mysql sepertinya sudah harus siap-siap dari sekarang untuk merombak scriptnya memakai MySQLi.

Sebenarnya apa sih perbedaan antara MySQL dengan MySQLi? Pada dasarnya databasenya masih sama dengan SQL dan phpMyAdmin juga masih sama, hanya saja pada MySQLi suport object oriented maupun prosedural. Object oriented nya sendiri sudah build in, jadi tidak perlu untuk membuat class sendiri. Tapi yang menurut saya keren karena MySQLi tidak perlu diinstall, sehingga saat menggunakan hosting gratisan ext nya sudah ada, dan bisa dilihat dari phpinfo. Sedangkan di localhost bisa dilihat di php.ini, di situ sudah ada extension=php_mysqli.dll

Oh iya, trend saat ini, terutama situs-situs besar sudah mulai migrasi ke MariaDB 10, Namun bagi anda penggemar hosting gratisan tentu tidak bisa menginstall MariaDB, jadi MySQLi saya pikir solusi yang tepat.

Kelebihan lain dari MySQLi dibandingkan dengan MySQL adalah support prepared statement, yang mana banyak orang menggunakannya untuk menangkal SQL Injection. Untuk prepared statement ini akan saya bahas di lain waktu (gak janji).

Soal proseduralnya, MySQLi sebenarnya tidak berbeda jauh dengan MySQL MySQL:

$conect = mysql_connect($host, $user, $pass);

MySQLi:

$conect = mysqli_connect($host, $user, $pass, $db);

MySQL:

$user = mysql_query(‘SELECT * FROM `user` WHERE `nama`=”subur”‘, $conect); $data = mysql_fetch_row($user); echo $data[1];

MySQLi:

$user = mysqli_query($conect, ‘SELECT * FROM `user` WHERE `nama`=”subur”‘); $data = mysqli_fetch_row($user); echo $data[1]; mysqli_close($conect);

MySQL:

mysql_real_escape_string($nama) MySQLi:

mysqli_real_escape_string($conect, $nama)

Untuk bagian yang bersifat fundamental masih sama, seperti:

$user = “root”; $pass = “root”; $host = “localhost”; $db = “mydb”;

(10)

What’s New in OpenText

TM

Gupta Team Developer 7.0

TD developers can simply pass UDVs

(user defined variables) when calling the service

without the complex and time consuming need to

construct the JSON string. The same is true when

receiving data from a REST service, the received

JSON string is automatically parsed and assigned to

UDV member variables saving lots of time and effort

that would be required for manual JSON parsing.

(11)

Introducing JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

 A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

 An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace) . Each name is followed by : (colon) and the name/value pairs are separated by , (comma) .

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket) . Values are separated by , (comma) .

(12)

A value can be a string in double quotes, or a number, or true or false or null , or an object or an array. These structures can be nested.

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

(13)

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

(14)

PHP

Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP:

Certain character sequences beginning with backslash (\) are replaced with special characters

Variable names (starting with $) are replaced with string representations of their values.

The escape-sequence replacements are:

\n is replaced by the newline character

\r is replaced by the carriage-return character

\t is replaced by the tab character

\$ is replaced by the dollar sign itself ($)

\" is replaced by a single double-quote (")

\\ is replaced by a single backslash (\)

<?

$variable = "name";

$literally = 'My $variable will not print!\\n';

print($literally);

$literally = "My $variable will print!\\n";

print($literally);

?>

My $variable will not print!\n My name will print

The foreach loop statement

The foreach statement digunakan untuk loop didalam suatu arrays.

For each mengirim value dari

current array element menuju ke $value dan si pointer array dipindahkan satu persatu dan pengiriman element berikutnnya akan di proses.

foreach (array as value) {

code to be executed;

}

<html>

<body>

<?php

$matriks = array( 1, 2, 3, 4, 5);

foreach( $ matriks as $harga ) {

echo "Value is $ harga <br />";

}

?>

</body>

</html>

Value is 1

Value is 2

Value is 3

Value is 4

Value is 5

(15)

PHP ─ Arrays

Array adl structure data yg menyimpan one / lebih type values yg sama dalam sebuah value tunggal.

eg, jika ingin simpan 100 numbers, maka drpd mendefinisikan 100 variables, lebih sederhana untuk mendefinisikan sebuah array yg 100 sat panjang.

There are three different kind of arrays and each array value is accessed using an ID which is called array index.

Numeric array - An array dengan indeks numerik. Values disimpan dan diakses dalam cara yg linear

Associative array - An array dgn strings sebagai indeksnya. Menyimpan harga elemen values dalam association dengan nama kunci berbeda a strict linear index order.

Multidimensional array - An array mengandung satu / lebih arrays dan harganya diakses using multiple indices.

NOTE: Built-in array functions is given in function reference PHP Array Functions

Numeric Array

Dapat menyimpan angka, strings dan bermacam macam object tetapi indeksnya akan direpresentasikan sebagai angka.

array indeks Standarnya dimulai dari nol.

Example

The following example demonstrates how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>

<body>

<?php

/* First method to create array. */

$numbers = array( 1, 2, 3, 4, 5);

foreach( $numbers as $value ) {

echo "Value is $value <br />";

}

/* Second method to create array. */

$numbers[0] = "one";

$numbers[1] = "two";

$numbers[2] = "three";

$numbers[3] = "four";

$numbers[4] = "five";

foreach( $numbers as $value ) {

echo "Value is $value <br />";

}

?>

</body>

</html>

Value is 1

Value is 2

Value is 3

Value is 4

Value is 5

Value is one

Value is two

Value is three

(16)

Value is four Value is five

ASOSIASI Arrays

The associative arrays sangat mirip dengan numeric arrays dalam fungsionalitasnya

Akan tetapi berbeda dalam betnuk indeksnya. Associative array akan punya indeks sebagai string dimana dapat establish a strong association antara key and values.

Untuk menyimpan gaji pegawai dalam array,sebuah indeks array numerically tidak akan menjadi pilihan terbaik.

Instead, kita dapat menggunakan nama pegawai sebagai keys dalam associative array, dan value akan menjadi their respective salary.

NOTE: Don't keep associative array inside double quote while printing, otherwise it would not return any value

<html>

<body>

<?php

/* First method to associate create array. */

$salaries = array(

"mohammad" => 2000,

"qadir" => 1000,

"zara" => 500 );

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";

echo "Salary of qadir is ". $salaries['qadir']. "<br />";

echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */

$salaries['mohammad'] = "high";

$salaries['qadir'] = "medium";

$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";

echo "Salary of qadir is ". $salaries['qadir']. "<br />";

echo "Salary of zara is ". $salaries['zara']. "<br />";

?>

</body>

</html>

Salary of mohammad is 2000 Salary of qadir is 1000 Salary of zara is 500 Salary of mohammad is high Salary of qadir is medium Salary of zara is low

Multidimensional Arrays

A multi-dimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Example

In this example, we create a two dimensional array to store marks of three students in three subjects:

<html>

<body>

(17)

<?php

$marks = array(

"mohammad" => array (

"physics" => 35,

"maths" => 30,

"chemistry" => 39 ),

"qadir" => array (

"physics" => 30,

"maths" => 32,

"chemistry" => 29 ),

"zara" => array (

"physics" => 31,

"maths" => 22,

"chemistry" => 39 )

);

/* Accessing multi-dimensional array values */

echo "Marks for mohammad in physics : " ; echo $marks['mohammad']['physics'] . "<br />";

echo "Marks for qadir in maths : ";

echo $marks['qadir']['maths'] . "<br />";

echo "Marks for zara in chemistry : " ; echo $marks['zara']['chemistry'] . "<br />";

?>

</body>

</html>

{

"mohammad":{

"physics":35,"maths":30,"chemistry":39 }

,

"qadir":{

"physics":30,"maths":32,"chemistry":29 }

,

"zara":{

"physics":31,"maths":22,"chemistry":39 }

}

(18)

PHP ─ GET and POST Methods

There are two ways the browser client can send information to the web server.

The GET Method

The POST Method

Before the browser sends the information, it encodes it using a scheme called URL

encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.

name1=value1&name2=value2&name3=value3

Spaces are removed and replaced with the + character and any other non-alphanumeric characters are replaced with a hexadecimal values. After the information is encoded, it is sent to the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.

http://www.test.com/index.htm?name1=value1&name2=value2

The GET method produces a long string that appears in your server logs, in the browser's Location: box.

METODE GET DIBATASI MAKSIMUM HANYA 1024 characters SAJA.

Never use GET method if you have password or other sensitive information to be sent to the server.

GET TIDAK BISA KIRIM BINER data, SEPERTI images ATAU word documents MENUJU server.

The data sent by GET method DAPAT DIAKSES DENGAN variable environment QUERY_STRING.

The PHP provides $_GET associative array to access all the sent information using GET method.

Try out the following example by putting the source code in test.php script.

<?php

if( $_GET["name"] || $_GET["age"] ) {

echo "Welcome ". $_GET['name']. "<br />";

echo "You are ". $_GET['age']. " years old.";

exit();

}

?>

<html>

<body>

<form action="<?php $_PHP_SELF ?>" method="GET">

Name: <input type="text" name="name" />

Age: <input type="text" name="age" />

<

Referensi

Dokumen terkait