Anda di halaman 1dari 46

PHP ADVANCED

Part 2 / Pertemuan #8
File Upload
• Pastikan instruksi file_uploads = On pada
file “php.ini”.
• Buat form HTML untuk upload file

<form action="upload.php" method="post“


enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
File Upload
• Buat file upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
• Script PHP menjelaskan:

$ target_dir = "uploads /" - menentukan direktori


tempat file akan ditempatkan
$ target_file menentukan jalur file yang akan
diunggah
$ uploadOk = 1 belum digunakan (akan digunakan
nanti)
$ imageFileType memegang ekstensi file dari file
(dalam huruf kecil)
Selanjutnya, periksa apakah file gambar adalah
gambar yang sebenarnya atau gambar palsu
Cek Eksistensi File
• Periksa apabila file sudah ada akan
muncul pesan error

// Cek eksistensi file


if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
Membatasi Ukuran File
• Membatasi ukuran <= 500KB

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Membatasi Jenis File
• Membatasi jebis file JPG, JPEG, PNG dan GIF

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
Code Lengkap
Cookie
• Cookie sering digunakan untuk mengidentifikasi
pengguna. Cookie adalah file kecil yang disematkan
oleh server di komputer pengguna. Setiap kali
komputer yang sama meminta halaman dengan
browser, itu juga akan mengirimkan cookie. Dengan
PHP, Anda dapat membuat dan mengambil nilai-nilai
cookie.
• Cookie dibuat dengan fungsi setcookie()
• Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>
Modifikasi Cookie
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>
Delete Cookie

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>
Cek cookie enable
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>

</body>
</html>
Session
• Session adalah suatu cara untuk
menyimpan informasi (dalam variabel)
untuk digunakan di beberapa halaman.

Tidak seperti cookie, informasi tidak


disimpan di komputer pengguna.
Session
Saat Anda bekerja dengan aplikasi, Anda membukanya,
melakukan beberapa perubahan, dan kemudian Anda
menutupnya. Ini seperti sebuah sesi. Komputer tahu siapa
Anda. Ia tahu kapan Anda memulai aplikasi dan ketika
Anda mengakhiri. Tetapi di internet ada satu masalah:
server web tidak tahu siapa Anda atau apa yang Anda
lakukan, karena alamat HTTP tidak mempertahankan
status.Variabel sesi memecahkan masalah ini dengan
menyimpan informasi pengguna untuk digunakan di
beberapa halaman (mis. Nama pengguna, warna favorit,
dll). Secara default, variabel sesi berlangsung hingga
pengguna menutup browser.Begitu; Variabel sesi
memegang informasi tentang satu pengguna tunggal, dan
tersedia untuk semua halaman dalam satu aplikasi.
Memulai Sebuah Session PHP
Fungsi session_start() digunakan untuk memulai sebuah session.
Variabel-variabel session diatur dengan variabel global PHP:
$_SESSION.
<?php demo_session1.php
// Start the session
session_start();
?> Fungsi session_start() harus disebut
<!DOCTYPE html>
paling awal sebelum tag HTML apapun
<html>
<body>
dalam dokumen

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>
Mengakses Session
• Membuat file demo_session2.php utk mengakses informasi session
pada demo_session1.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>
Modifikasi Session
• Untuk modifikasi session cukup dengan menulis ulang (overwrite)
nya:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>
Menghapus Session
• Gunakan fungsi session_unset() dan session_destroy() untuk
menghapus seluruh variabel session global dan menghapus session:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>
Filter
• Validasi data: Memilah jika data sesuai dengan form
• Sanitasi data: menyingkirkan setiap karakter ilegal dari
data
• Filter PHP digunakan untuk memvalidasi dan
membersihkan input eksternal.

Ekstensi filter PHP memiliki banyak fungsi yang


diperlukan untuk memeriksa input pengguna, dan
dirancang untuk membuat validasi data lebih mudah
dan lebih cepat.

Fungsi filter_list () dapat digunakan untuk


mencantumkan apa yang ditawarkan ekstensi filter
PHP:
Filter PHP
• Banyak aplikasi web menerima masukan eksternal.
Input / data eksternal dapat berupa:

Masukan pengguna dari formulir


Cookie
Data layanan web
Variabel server
Hasil query basis data

Anda harus selalu memvalidasi data eksternal!


Data yang dikirim tidak valid dapat menyebabkan
masalah keamanan dan merusak halaman web Anda!
Dengan menggunakan filter PHP Anda dapat yakin
aplikasi Anda mendapat masukan yang benar!
Fungsi filter_var()
• Fungsi filter_var () memvalidasi dan
membersihkan data.
• Fungsi filter_var () menyaring variabel
tunggal dengan filter yang ditentukan.
• Diperlukan dua bagian data:
– Variabel yang ingin Anda periksa
– Jenis pemeriksaan yang akan digunakan
Sanitize a String
• Contoh menggunakan fungsi filter_var() untuk
menghilangkan semua tag HTML dalam suatu String

<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
Validasi Integer
• Memvalidasi suatu nilai variabel integer atau bukan

<?php
$int = 100;

if (!filter_var($int, FILTER_VALIDATE_INT) === false) {


echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
Validasi Integer
• Memvalidasi suatu nilai variabel integer atau bukan

<?php
$int = 0;

if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int,


FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
Validasi Integer dalam suatu
range
• Memvalidasi suatu nilai variabel dalam range integer

<?php
$int = 122;
$min = 1;
$max = 200;

if (filter_var($int, FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min,


"max_range"=>$max))) === false) {
echo("Variable value is not within the legal range");
} else {
echo("Variable value is within the legal range");
}
?>
Validasi IP Address
• Memvalidasi suatu nilai variabel sebagai alamat IP

<?php
$ip = "127.0.0.1";

if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {


echo("$ip is a valid IP address");
} else {
echo("$ip is not a valid IP address");
}
?>
Sanitize & Validate Email Addr
• Memvalidasi suatu nilai variabel sebagai alamat email

<?php
$email = “p.rakasa@mailX.com";

// Remove all illegal characters from email


$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Sanitize & Validate URL
• Memvalidasi suatu nilai variabel sebagai alamat URL

<?php
$url = "https://www.facebook.com";

// Remove all illegal characters from a url


$url = filter_var($url, FILTER_SANITIZE_URL);

// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
Error Handling
• Saat membuat skrip dan aplikasi web, penanganan kesalahan
adalah bagian yang penting. Jika kode Anda tidak memiliki kode
pengecekan kesalahan, program Anda mungkin terlihat sangat
tidak profesional dan Anda mungkin terbuka terhadap risiko
keamanan.

Tutorial ini berisi beberapa metode pemeriksaan kesalahan yang


paling umum di PHP.

Kami akan menunjukkan metode penanganan kesalahan yang


berbeda:

Pernyataan "die ()" sederhana


Kesalahan khusus dan pemicu kesalahan
Pelaporan kesalahan
Basic: fungsi die()
• Memaksa menghentikan script yang error

<?php
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
?>
Adv: membuat fungsi custom
• Membuat fungsi khusus/ custom sebagai error handler
yaitu membuat fungsi khusus yang bisa dipanggil ketika
kesalahan terjadi di PHP.
• Fungsi ini harus mampu menangani minimal dua
parameter (tingkat kesalahan dan pesan kesalahan)
tetapi dapat menerima hingga lima parameter
(opsional: file, nomor baris, dan konteks kesalahan)
Adv: membuat fungsi custom
Parameter Description
Required. Specifies the error report level for the user-defined
error_level error. Must be a value number. See table below for possible
error report levels
Required. Specifies the error message for the user-defined
error_message
error
error_file Optional. Specifies the filename in which the error occurred
error_line Optional. Specifies the line number in which the error occurred
Optional. Specifies an array containing every variable, and
error_context
their values, in use when the error occurred

error_function(error_level,error_message,
error_file,error_line,error_context)
Error Handler

<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}

//set error handler


set_error_handler("customError");

//trigger error
echo($test);
?>
Fungsi trigger_error()

<?php
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below");
}
?>
Fungsi trigger_error()
<?php
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below");
}
?>

Kesalahan dapat dipicu di mana pun Anda inginkan dalam skrip, dan dengan
menambahkan parameter kedua, Anda dapat menentukan tingkat kesalahan apa yang
dipicu.

Kemungkinan jenis kesalahan:

E_USER_ERROR - Kesalahan run-time fatal yang dibuat pengguna. Kesalahan yang


tidak dapat dipulihkan dari. Eksekusi skrip dihentikan
E_USER_WARNING - Peringatan run-time yang dibuat pengguna non-fatal. Eksekusi
skrip tidak terhenti
E_USER_NOTICE - Default. Notifikasi waktu-run yang dibuat oleh pengguna. Skrip
menemukan sesuatu yang mungkin merupakan kesalahan, tetapi bisa juga terjadi
ketika menjalankan skrip secara normal
Contoh lengkap
Dalam contoh ini, E_USER_WARNING muncul jika variabel "uji" lebih besar
dari "1". Jika E_USER_WARNING terjadi, kami akan menggunakan handler
kesalahan khusus dan mengakhiri skrip
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}

//set error handler


set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Mengirim Pesan Error via Email
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");
}

//set error handler


set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Exception
• Exception handling is used to change the
normal flow of the code execution if a
specified error (exceptional) condition
occurs. This condition is called an
exception.
• Exceptions should only be used with error
conditions, and should not be used to
jump to another place in the code at a
specified point.
Penggunaan Dasar Exception
• When an exception is thrown, the code following it will not be executed,
and PHP will try to find the matching "catch" block.
• If an exception is not caught, a fatal error will be issued with an
"Uncaught Exception" message.
• Example throw an exception without catching it

<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception
checkNum(2);
?>
Try, Throw & Catch
• To avoid the error from the example above, we need to
create the proper code to handle an exception.
• Proper exception code should include:
• try - A function using an exception should be in a "try"
block. If the exception does not trigger, the code will
continue as normal. However if the exception triggers,
an exception is "thrown"
• throw - This is how you trigger an exception. Each
"throw" must have at least one "catch"
• catch - A "catch" block retrieves an exception and
creates an object containing the exception information
Contoh Exception yg tepat
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}

//trigger exception in a "try" block


try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}

//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
Contoh Exception Class
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example...com";

try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}

catch (customException $e) {


//display custom message
echo $e->errorMessage();
}
?>
Contoh Multiple Exception
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example.com";

try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE) {
throw new Exception("$email is an example e-mail");
}
}

catch (customException $e) {


echo $e->errorMessage();
}

catch(Exception $e) {
echo $e->getMessage();
}
?>
Top Level Exception Handler
The set_exception_handler() function sets a user-defined function to
handle all uncaught exceptions

<?php
function myException($exception) {
echo "<b>Exception:</b> " . $exception->getMessage();
}

set_exception_handler('myException');

throw new Exception('Uncaught Exception occurred');


?>

Anda mungkin juga menyukai