Arsip Kategori: PHP

Mengamankan Data Input User

Pada artikel sebelumnya, saya telah menuliskan tentang cara Membuat Script Login yang Aman dengan PHP dan MySQL. Kali ini saya akan berikan sekali lagi cara mengamankan data yang di-input oleh user.

Jika kita ingin mendapatkan data dari user, tentu kita sediakan field input. Pada dasarnya user dapat memasukan apa saja dalam field input tersebut.

“Never trust user data”

Nah, supaya data yang diinput oleh user itu aman, kita perlu melakukan validasi terhadap data tersebut.
Caranya?

1. Pakai PHP strip_tags()
Contoh:
<?php
$user_input = "alert(‘AWAS!’);”;
echo strip_tags($user_input);
?>

2. Pakai trim(htmlspecialchars())
Contoh:
<?php
$user_input = "alert(‘AWAS’);”;
echo trim(htmlspecialchars($user_input));
}
?>

3. Pakai filter_input()
Contoh:
<?php
$user_input = "alert(‘AWAS’);”;
echo filter_input($user_input, FILTER_SANITIZE_STRIPPED);
?>

Untuk filter_input() tersedia beberapa pilihan filter.
Contoh:
filter_input($user_input, FILTER_SANITIZE_STRIPPED);
filter_input($user_input, FILTER_SANITIZE_STRING);
filter_input($user_input, FILTER_VALIDATE_EMAIL);
filter_input($user_input, FILTER_VALIDATE_INT);
filter_input($user_input, FILTER_VALIDATE_URL);

Anda bisa baca perbedaannya di sini https://www.php.net/manual/en/filter.filters.sanitize.php

Jadi supaya data yang di-input oleh user itu aman, sebenarnya kita cukup berikan filter_input() pada setiap field yang di-input oleh user. Pastikan setelah di-filter datanya sesuai yang kita mau ya…

Selamat mencoba. Semoga sukses.

Membuat Script Login yang Aman dengan PHP dan MySQL

Sebuah aplikasi berbasis web umumnya membutuhkan halaman login bagi user/member untuk mengakses halaman tertentu. Halaman itu tentunya harus aman dari resiko pembobolan dan pencurian data.

Kali ini saya akan mencoba memberikan sedikit tips cara membuat script login yang aman dengan PHP dan MySQL.
Script ini hanya memberikan gambaran tentang bagaimana cara mengamankan halaman login dari ancaman dan resiko pembobolan dan pencurian data user/member. Script ini juga menggunakan teknik enkripsi password dengan fungsi hash(sha512) dan salt.
Saya tidak meng-klaim script ini benar-benar dapat membuat halaman login yang aman karena masalah keamanan system web tentu lebih luas dan kompleks.
Semoga tips berikut ini bisa menambah pengetahuan Anda dalam mengamankan aplikasi web Anda.

Script Login berikut ini diharapkan dapat menahan halaman web Anda dari serangan:
SQL Injections
Session Hijacking
Network Sniffing
Cross Site Scripting
Brute Force Attacks

Script ini jalan di PHP minimal versi 5.4 dan MySQL versi 5.0

Pertama kita siapkan databasenya.

1. Create Database login:

CREATE DATABASE `login`;

2. Create user untuk akses database tersebut. Hindari menggunakan user default root MySql.

CREATE USER 'admin_db'@'localhost' IDENTIFIED BY 'eKcGZr59zAa2BEWU';
GRANT SELECT, INSERT, UPDATE ON `login`.* TO 'sec_user'@'localhost';

3. Create tabel login_attempts untuk menyimpan data percobaan login oleh user. Dengan demikian kita bisa menahan serangan brute force attack

CREATE TABLE `login_attempts` (
    `user_id` INT(11) NOT NULL,
    `time` VARCHAR(30) NOT NULL
) ENGINE=InnoDB

4. Create tabel members dengan 5 field: id, username, email, password dan salt.
Khusus pada field password kita gunakan tipe CHAR(128) untuk menyimpan data password yang di encrypt dengan fungsi hash(sha512) dan salt .

CREATE TABLE `secure_login`.`members` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `username` VARCHAR(30) NOT NULL,
    `email` VARCHAR(50) NOT NULL,
    `password` CHAR(128) NOT NULL,
    `salt` CHAR(128) NOT NULL 
) ENGINE = InnoDB;

5. Insert 1 row data user admin ke tabel members untuk test login.

INSERT INTO `login`.`members` VALUES(1, 'admin_user', 'admin@kampushendra.com',
'00807432eae173f652f2064bdca1b61b290b52d40e429a7d295d76a71084aa96c0233b82f1feac45529e0726559645acaed6f3ae58a286b9f075916ebf66cacc',
'f9aab579fc1b41ed0c44fe4ecdbfcdb4cb99b9023abb241a6db833288f4eea3c02f76e0d35204a8695077dcf81932aa59006423976224be0390395bae152d4ef');

Berikutnya kita siapkan script PHP-nya.

1. Create folder “includes” di luar folder root aplikasi web Anda (misal: xampp/apps/includes/)

2. Create file psl-config.php berikut ini lalu simpan di folder includes:

<?php
/** These are the database login details */  
define("HOST", "localhost");    // The host you want to connect to.
define("USER", "admin_db");    // The database username. 
define("PASSWORD", "eKcGZr59zAa2BEWU");  // The database password. 
define("DATABASE", "login");     // The database name.
define("CAN_REGISTER", "any");
define("DEFAULT_ROLE", "member");
define("SECURE", FALSE);    // FALSE for Dev, TRUE for Prod using https
?>

3. Create file db_connect.php berikut ini lalu simpan di folder includes:

<?php
include_once 'psl-config.php';   // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);

4. Create file functions.php berikut ini lalu simpan di folder includes:

<?php
include_once 'psl-config.php';
function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name
    $secure = SECURE;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);
    // Sets the session name to the one set above.
    session_name($session_name);
    session_start();              // Start the PHP session 
    session_regenerate_id(true);  // regenerated the session, delete the old one. 
}

//This login function will check the email and password against the database. 
//It will return true if there is a match.
function login($email, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT id, username, password, salt 
        FROM members  WHERE email = ?  LIMIT 1")) {
        $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();
        // get variables from result.
        $stmt->bind_result($user_id, $username, $db_password, $salt);
        $stmt->fetch();
 
        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($stmt->num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts 
 
            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                "", 
                                                                $username);
                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512', 
                              $password . $user_browser);
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', '$now')");
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}

//This checkbrute function will hold login tries for 2 hour if 5 logins failed.
function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time 
    $now = time();
     // All login attempts are counted from the past 2 hours. 
    $valid_attempts = $now - (2 * 60 * 60);
     if ($stmt = $mysqli->prepare("SELECT time 
                             FROM login_attempts 
                             WHERE user_id = ? 
                            AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);
         // Execute the prepared query. 
        $stmt->execute();
        $stmt->store_result();
         // If there have been more than 5 failed logins 
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    }
}
//This login_check function will Check if all session variables are set
function login_check($mysqli) {
    if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];
         // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];
         if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter. 
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();
             if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);
                if ($login_check == $login_string) {
                    // Logged In!!!! 
                    return true;
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    } else {
        // Not logged in 
        return false;
    }
}
//This login_check function will sanitizes URL from the PHP_SELF server variable
function esc_url($url) {
     if ('' == $url) {
        return $url;
    }
    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;
     $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }
    $url = str_replace(';//', '://', $url);
    $url = htmlentities($url);
    $url = str_replace('&amp;', '&', $url);
    $url = str_replace("'", ''', $url);
    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}

5. Create file process_login.php berikut ini lalu simpan di folder aplikasi web Anda (Misal: //xampp/htdocs/myweb/)

<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
    $email = $_POST['email'];
    $password = $_POST['p']; // The hashed password.
    if (login($email, $password, $mysqli) == true) {
        // Login success 
        header('Location: ../protected_page.php');
    } else {
        // Login failed 
        header('Location: ../index.php?error=1');
    }
} else {
    // The correct POST variables were not sent to this page. 
    echo 'Invalid Request';
}

6. Create file logout.php berikut ini lalu simpan di folder aplikasi web Anda (Misal: //xampp/htdocs/myweb/)

<?php
include_once 'functions.php';
sec_session_start();
// Unset all session values 
$_SESSION = array();
// get session parameters 
$params = session_get_cookie_params();
// Delete the actual cookie. 
setcookie(session_name(),'', time() - 42000,
        $params["path"], 
        $params["domain"], 
        $params["secure"], 
        $params["httponly"]);
// Destroy session 
session_destroy();
header('Location: ../index.php');

7. Create file index.php berikut ini lalu simpan di folder aplikasi web Anda (Misal: //xampp/htdocs/myweb/)
File index.php adalah halaman login Anda.

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
    $logged = 'in';
} else {
    $logged = 'out';
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Secure Login: Log In</title>
    <script type="text/JavaScript" src="js/sha512.js"></script> 
    <script type="text/JavaScript" src="js/forms.js"></script> 
</head>
<body>
        <?php
        if (isset($_GET['error'])) {
            if(@$_SESSION['error']==2)
		echo '<p class="error">Account is locked due to 5 failed logins!</p>';
	    else 
		echo '<p class="error">Error Logging In!</p>';
        }
        ?> 
        <form action="includes/process_login.php" method="post" name="login_form">                      
            Email: <input type="text" name="email" />
            Password: <input type="password" name="password" id="password"/>
            <input type="button" value="Login" 
                   onclick="formhash(this.form, this.form.password);" /> 
        </form>
<?php
        if (login_check($mysqli) == true) {
            echo '<p>Currently logged ' . $logged . ' as ' . htmlentities($_SESSION['username']) . '.</p>';
 
            echo '<p>Do you want to change user? <a href="includes/logout.php">Log out</a>.</p>';
        } else {
            echo '<p>Currently logged ' . $logged . '.</p>';
            echo "<p>If you don't have a login, please <a href='register.php'>register</a></p>";
                }
?>      
</body>
</html>

8. Create file protected_page.php berikut ini lalu simpan di folder aplikasi web Anda
File protected_page.php adalah halaman member yang bisa diakses setelah berhasil login.

<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
sec_session_start(); 
if(login_check($mysqli) == false) {
    echo 'You are not authorized to access this page, please login.';
    exit();
}

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Secure Login: Protected Page</title>
        <link rel="stylesheet" href="styles/main.css" />
    </head>
    <body>
        <?php if (login_check($mysqli) == true) : ?>
            <p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
            <p>
                This is an example protected page.  To access this page, users
                must be logged in.  At some stage, we'll also check the role of
                the user, so pages will be able to determine the type of user
                authorised to access the page.
            </p>
            <p>Return to <a href="index.php">login page</a></p>
        <?php else : ?>
            <p>
                <span class="error">You are not authorized to access this page.</span> 
Please <a href="index.php">login</a>.
            </p>
        <?php endif; ?>
    </body>
</html>

9. Create folder js di dalam folder aplikasi web Anda (Misal: //xampp/htdocs/myweb/js/)

10. Download file sha512.js dan forms.js lalu simpan di folder js

Setelah semua file siap, Anda dapat mencoba script login ini di web browser Anda.

Untuk script selengkapnya bisa Anda download dari sumber berikut ini:
https://github.com/peredurabefrog/phpSecureLogin

Preview, Resized dan Upload Gambar

Preview dan Upload Resized Image

Preview dan Upload Resized Image

Bagaimana cara upload gambar, dimana gambar yang mau diupload bisa di-preview dulu?
Nah… kali ini saya berikan coding untuk preview gambar yang mau diupload.
Disini juga diberikan cara untuk resized gambar sesuai dengan resolusi yang diinginkan.

Untuk upload file gambar, kita sediakan dulu HTML form dengan input type file berikut ini.
Ketika kita memilih file gambar yang akan di upload, maka gambar tersebut akan tampil di bagian div class preview.
Ini dilakukan oleh coding Javascript dengan nama fungsi readURL().

Dalam fungsi readURL() juga dimasukan coding untuk validasi apakah file yang dipilih itu adalah file gambar (.jpg) atau bukan.

Tombol “Upload Now” juga diberikan validasi checkSize() untuk memeriksa ukuran file yang mau diupload. Pada contoh coding ini diberikan batas ukuran file yang mau diupload adalah 200KB.

<html>
<head>
<title>Preview dan Upload Resized Image</title>
<style>
div.preview {max-width:300px;height:200px;border:10px solid #000000;}
img.preview {width:100%;height:100%;}
</style>
<script>
function checkSize(max_img_size)
{   var input = document.getElementById("imgfile");
    if(input.files.length==0)
	{	alert("Pilih file lebih dulu!");
		return false;
	}
	if(input.files && input.files.length == 1)
    {   if (input.files[0].size > max_img_size) 
        {  alert("Ukuran file harus di bawah " 
                  + (max_img_size/1024) + " KB");
            return false;
        }
    }
	return true;
}
</script>
</head>
<body>
<h1>Preview dan Upload Resized Image</h1>
<div class="preview"><img class="preview" id="prevImage" src="noimagepreview.png" alt="Preview Image" /></div>
<br/>
<form id="Imgfrm" method="post" enctype="multipart/form-data" onsubmit="return checkSize(204800);">
	Select JPG file: <input name="uploadedfile" id="imgfile" type="file" onchange="readURL(this)"; /> 
	<input type="submit" name="upload" value="Upload Now" /> 
</form>
<script>
function readURL(input)
{ 	var ext = input.value.split('.').pop().toLowerCase();
	if (ext!='jpg')
	{	alert("Pilih file JPG!");}
	else 
	{	if (input.files && input.files[0])
		{	var reader = new FileReader();
			reader.onload = function (e)
			{document.getElementById('prevImage').src=e.target.result;}
			reader.readAsDataURL(input.files[0]);
		}
	}
}
</script>
</body>
</html>

Setelah HTML Form dan Validasi Javascript sudah dibuat, berikutnya adalah proses upload gambar dengan resize. Maksudnya adalah upload file dengan cara resize resolusi gambar.
Berikut ini coding PHP untuk proses upload gambar dengan resize.

<?php
function resize($newWidth, $targetFile, $originalFile)
{   $img = imagecreatefromjpeg($originalFile);
    list($width, $height) = getimagesize($originalFile);
    $newHeight = ($height / $width) * $newWidth;
    $tmp = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    if (file_exists($targetFile)) {unlink($targetFile);}
    imagejpeg($tmp, "$targetFile.jpg");
}
if(isset($_POST['upload']))
{	$uploadedfile = $_FILES['uploadedfile']['name'];
	$ext = strtolower(pathinfo($uploadedfile, PATHINFO_EXTENSION));
	if ($ext!='jpg') die ("Error: Harap Upload file JPG!");
	$target_path = "img/A01.jpg";
	resize('300' , $target_path , $uploadedfile);
}
?>

Selamat mencoba. Semoga berhasil.

Upload Download File dengan PHP

Upload Download File

Upload Download File

Pada kesempatan ini saya ingin memberikan coding untuk upload dan download file dengan web browser.
Upload dan download file merupakan fitur yang umum digunakan di sebuah website.

Untuk membuat fitur upload, kita sediakan HTML form dengan atribut-atribut sebagai berikut.

<form enctype="multipart/form-data" 
      action="uploader.php" 
      method="post" 
      onsubmit="return checkSize(1048576);">
<input type="file" id="fileupload" name="uploadedfile"  />
<input type="submit" value="Upload File" />

Kemudian sediakan field dengan tag input bertipe “file” dan sebuah tombol “Upload File” dengan tag input bertipe ‘submit’. Jika tombol tersebut di click maka akan menjalankan file uploader.php yang ditulis pada form atribut action. Sebelum uploader.php dijalankan, form akan melakukan validasi dengan fungsi javascript checksize(1048576), yakni fungsi javascript untuk membatasi ukuran file yang diupload maksimum 1048576 Bytes atau 1 MB.

Berikut ini coding selengkapnya. Coding ini Anda simpan dengan nama file “index.php”.
Coding dibawah ini berisi form upload dan HTML table yang berisi file yang telah di upload.
Juga link untuk download filenya.

<!doctype html>
<html>
<head>
<title>Upload Download File</title>
<style>
html, body {font:12px Arial,Helvetica,sans-serif;}
fieldset {border:1px solid #ff0000; width:400px;}
legend {border:1px solid #ff0000;}
table {border-collapse:collapse;width:500px;}
td, th {border:1px solid #c0c0c0;padding:5px;}
th{background:#ff0000;color:#ffffff;}
</style>
<script type="text/javascript">
function checkSize(max_img_size)
{   var input = document.getElementById("fileupload");
    if(input.files && input.files.length == 1)
    {	if (input.files[0].size > max_img_size) 
        {  alert("Ukuran file harus di bawah " 
                  + (max_img_size/1024/1024) + " MB");
            return false;
        }
    }
    return true;
}
</script>
</head>
<body>
<form enctype="multipart/form-data" action="uploader.php" method="post" 
      onsubmit="return checkSize(1048576);">
<fieldset>
<legend>Upload File Max 1 MB</legend>
Choose a file to upload: <input name="uploadedfile" type="file" id="fileupload" /><br />
<input type="submit" value="Upload File" />
</fieldset>
</form>
<br/>
<table>
<tr>
<th>File Name</th>
<th>Upload Date</th>
<th>Type</th>
<th>Size</th>
<th>Delete</th>
</tr>
<?php
if ($handle = opendir('./files/'))
{	while (false !== ($file = readdir($handle)))
    {   if($file!=="." && $file !=="..")
	{	echo "<tr><td><a href=\"download.php?id=" . urlencode($file). "\">$file</a></td>";
		echo "<td>" . date ("m/d/Y H:i", filemtime("files/".$file)) . '</td>';
		echo "<td>" . pathinfo("files/".$file, PATHINFO_EXTENSION) . ' file </td>';
		echo "<td>" . round(filesize("files/".$file)/1024) . ' KB</td>';
		echo "<td><a href=\"hapus.php?id=$file\">Del</a></td></tr>";
        }
    }
    closedir($handle);
}
?>
</table>
</body>
</html>

Berikut ini coding untuk proses upload file. Coding ini Anda simpan dengan nama file “uploader.php”.
Coding ini akan dijalankan ketika tombol “Upload File” di click.

<?php
$target_path = "files/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{ header("Location: index.php");}
else {echo "Error uploading file. Please try again!";}
?>

Coding berikutnya adalah untuk proses download file. Untuk download file yang telah diupload, kita sediakan link di HTML table yang ada di file index.php diatas.
Coding di bawah ini Anda simpan dengan nama file “download.php”.

<?php
$direktori = "./files/";
$filename = $_GET['id'];
if(file_exists($direktori.$filename)){
	$file_extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
	switch($file_extension){
	  case "pdf": $ctype="application/pdf"; break;
	  case "exe": $ctype="application/octet-stream"; break;
	  case "zip": $ctype="application/zip"; break;
	  case "rar": $ctype="application/rar"; break;
	  case "doc": $ctype="application/msword"; break;
	  case "xls": $ctype="application/vnd.ms-excel"; break;
	  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
	  case "gif": $ctype="image/gif"; break;
	  case "png": $ctype="image/png"; break;
	  case "jpeg":
	  case "jpg": $ctype="image/jpg"; break;
	  default: $ctype="application/octet-stream";
	}
	if ($file_extension=='php'){
	  echo "<h1>Access forbidden!</h1>
		<p>Please contact Administrator.</p>";
	  exit;
	}
	else{
	  header("Content-Type: octet/stream");
	  header("Pragma: private"); 
	  header("Expires: 0");
	  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	  header("Cache-Control: private",false); 
	  header("Content-Type: $ctype");
	  header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
	  header("Content-Transfer-Encoding: binary");
	  header("Content-Length: ".filesize($direktori.$filename));
	  readfile("$direktori$filename");
	  exit();   
	}
}else{  echo "<h1>Access forbidden!</h1>
	      <p>Please contact Administrator.</p>";
	exit;
}
?>

Coding terakhir ini adalah untuk delete file. Link untuk delete file juga ada di HTML table pada file index.php di atas.

<a href=\"hapus.php?id=$file\">Del</a>

Simpanlah coding di bawah ini dengan nama file “hapus.php”.

<?php
$id = $_GET["id"];
unlink("files/".$id);
header("location:index.php");
?>

Silakan Anda coba. Semoga sukses ya…

Export Data MySQL ke Excel .csv

Pada Aplikasi Web Database biasanya kita memerlukan fasilitas untuk export atau download data dari database MySQL ke Excel.

Kali ini saya akan berikan contoh coding PHP untuk membuat fasilitas export data MySQL ke dalam file .csv yang dapat dibuka dengan program Excel.

Contoh coding PHP berikut ini untuk mendownload data pada tabel “users di database “students”, berikut ini coding selengkapnya.

<?php
error_reporting(0);
date_default_timezone_set('Asia/Jakarta');
$Timestamp = date('Ymd@His');
// Connect to DB
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'students';
$tbl	= 'users';
$filename = "$tbl"."_"."$Timestamp".".csv";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname) or die ('Error connecting to db!');
// Get all fields names in the table.
$result = mysqli_query($conn,"SHOW COLUMNS FROM $tbl") or die("Error running query!");
$numofcol = mysqli_num_rows($result);
$out = '';
if ($numofcol > 0)
{   while ($row = mysqli_fetch_assoc($result))
	{	$out .='"'.$row['Field'].'",'; }
}
$out .="\n";
// Add all records in the table to $out.
$result=mysqli_query($conn,"SELECT * FROM $tbl") or die("Error run query");
while ($l = mysqli_fetch_array($result))
{	for ($i = 0; $i < $numofcol; $i++)
	{	$out .='"'.$l["$i"].'",'; }
	$out .="\n";
}
//Download $filename.csv
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary ");
echo $out;
//or save $out as $filename.csv on server
//file_put_contents($filename, $out);
?>

Jika Anda ingin menyimpan file csv di server, Anda tinggal membuka comment pada 2 baris terakhir.

Selamat mencoba, semoga sukses.

Membaca Email dengan PHP

Email IMAP

Membaca Email dengan PHP

PHP memiliki fungsi untuk mengambil dan membaca email melalui internet protokol POP3 dan IMAP. Port yang kita gunakan untuk itu adalah 993 (IMAP SSL)
Fungsi-fungsi yang digunakan adalah:

imap_open($hostname,$username,$password);
imap_fetch_overview($mbox,”1:$MN”,0);
imap_header($mbox, $msg);

Coding berikut ini menampilkan semua email dari GMail Anda, seperti pada gambar di atas.

<!DOCTYPE html>
<html>
<head>
<title>Baca Email</title>
<style type="text/css">
#mytable {width:800px;border:1px #a9c6c9 solid;font:12px verdana,arial,sans-serif;color:#333333;}
#mytable td {padding:8px;}
#mytable tr:hover td {background:#a0a0a0;color:#ffffff;}
#mytable th {background-color:#000099;color:#ffffff;padding:8px; }
#mytable tr:nth-child(odd) {background-color:#c0c0c0;}
#mytable tr:nth-child(even) {background-color:#f0f0f0;}
</style>
<script type="text/javaScript">
function buka(url)
{newwindow = window.open(url, '_blank', "status=yes, height=300, width=400, resizeable=yes");}
</script>
</head>
<body>
<?php
$hostname = '{imap.gmail.com:993/ssl/novalidate-cert}[Gmail]/All Mail';
$username = 'your_email@gmail.com';
$password = 'your_gmail_password';
$mbox = imap_open($hostname,$username,$password) or die('Cannot connect to mail server: ' . imap_last_error());
$MC=imap_check($mbox);
$MN=$MC->Nmsgs;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
$size=sizeof($overview);
echo "<h1>Baca Email</h1>
	<table id='mytable'>
	<tr><th>Msg_Id</th><th>From</th><th>Email</th><th>Date</th><th>Subject</th><th>Size</th></tr>";
for($i=$size-1;$i>=0;$i--)
{	$val=$overview[$i];
	$msg=$val->msgno;
	$date=date('Y-m-d H:i:s', strtotime($val->date));
	$subj=isset($val->subject)?$val->subject:"(no subject)";
	$header = imap_header($mbox, $msg);
	$from = $header->from;
	$email_size = $val->size;
	foreach ($from as $id => $object) 
	{	$fromname = isset($object->personal)?$object->personal:$object->mailbox;
		$fromaddress = $object->mailbox . "@" . $object->host;
	}
	echo "<tr onclick=\"buka('read_email.php?msgno=$msg&msgdate=$date&msgfrom=$fromname&msgemail=$fromaddress&msgsubj=$subj');\">
		<td>$msg</td> <td>$fromname</td> <td>$fromaddress</td> <td>$date</td> <td>$subj</td><td>$email_size</td></tr>";
}
echo "</table>";
imap_close($mbox);
?>
</body>
</html>

Anda dapat click baris pada table-nya untuk membaca isi email Anda pada window browser baru.

Berikut ini coding untuk membaca isi email Anda

<?php
function get_mime_type(&$structure)
{   $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
    if($structure->subtype) {return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;}
    return "TEXT/PLAIN";
}
function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false)
{   if (!$structure) {$structure = imap_fetchstructure($stream, $msg_number);}
    if($structure)
    {   if($mime_type == get_mime_type($structure))
        {   if(!$part_number) {$part_number = "1";}
            $text = imap_fetchbody($stream, $msg_number, $part_number);
            if($structure->encoding == 3) {return imap_base64($text);}
			else if ($structure->encoding == 4) {return imap_qprint($text);}
			else {return $text;}
        }
        if ($structure->type == 1) /* multipart */
        {   while (list($index, $sub_structure) = each($structure->parts))
            {   if ($part_number) {$prefix = $part_number . '.';}
                $data = get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
                if ($data) {return $data;}
            }
        }
    }
    return false;
}
$msg_number = $_GET['msgno'];
$msg_from = $_GET['msgfrom'];
$msg_email = $_GET['msgemail'];
$msg_date = $_GET['msgdate'];
$msg_subject = $_GET['msgsubj'];
$hostname = '{imap.gmail.com:993/ssl/novalidate-cert}[Gmail]/All Mail';
$username = 'your_email@gmail.com';
$password = 'your_gmail_password';
$stream = imap_open($hostname,$username,$password) or die('Cannot connect to mail server: ' . imap_last_error());
$isiemail = get_part($stream, $msg_number, "TEXT/HTML");
echo "<h2>$msg_subject</h2>
	  From: $msg_from ($msg_email) <br />
	  Date: $msg_date<br/>
	  <hr />
	  $isiemail";
?> 

Selamat mencoba, semoga sukses.

Send Email dengan PHP

SendEmail1

PHP memiliki fungsi mail() untuk mengirim email, dengan format:

$sent = @mail($to, $subject, $message, $headers);

Dimana $to adalah alamat email penerima, $subject adalah subyek emailm $message adalah isi/pesan emailnya dan $headers berisi email header yang formatnya harus sesuai dengan standard email yang dikirim.

Dibawah ini diberikan coding HTML berupa form email yang dapat diisi dengan parameter yang diperlukan oleh fungsi PHP tersebut. Email yang dikirim dapat berisi 1 file attachment.

Berikut ini coding PHP selengkapnya.

<?php
if(isset ($_POST["send"]))
{   $from = $_POST["from"];
    $to	= $_POST["to"];
    $subject = $_POST["subject"];
    $message = nl2br($_POST["msg"]);
    $upload_name = $_FILES["upload"]["name"];
    $upload_type = $_FILES["upload"]["type"];
    $upload_size = $_FILES["upload"]["size"];
    $upload_temp = $_FILES["upload"]["tmp_name"]; 

    $num = md5(time());
    //Normal headers
    $headers  = "From:".$from."\r\n";
    $headers  .= "MIME-Version: 1.0\r\n";
    $headers  .= "Content-Type: multipart/mixed; ";
    $headers  .= "boundary=".$num."\r\n";
    $headers  .= "--$num\r\n";
    // This two item help avoid spam
    $headers .= "Message-ID: <".gettimeofday(true)."-TheSystem@".$_SERVER['SERVER_NAME'].">\r\n";
    $headers .= "X-Mailer: PHP v".phpversion()."\r\n";
    // With html message
    $headers .= "Content-Type: text/html; charset=iso-8859-1\r\n"; 
    $headers .= "Content-Transfer-Encoding: 8bit\r\n";
    $headers .= "".$message."\n";
    $headers .= "--$num";
    // With Attachment
    if ($upload_name!="")
    {	$fp = fopen($upload_temp, "rb");
	$file = fread($fp, $upload_size);
	$file = chunk_split(base64_encode($file));
	$headers  .= "\nContent-Type:".$upload_type." ";
	$headers  .= "name=\"".$upload_name."\"r\n";
	$headers  .= "Content-Transfer-Encoding: base64\r\n";
	$headers  .= "Content-Disposition: attachment; ";
	$headers  .= "filename=\"".$upload_name."\"\r\n\n";
	$headers  .= "".$file."\r\n";
	$headers  .= "--".$num."--\n";
	fclose($fp);
    }
    else 
    { $headers .= "--\n"; } //close boundary
    // SEND MAIL
    $sent = @mail($to, $subject, $message, $headers);
    if($sent)
    {	echo 'Mail has been sent! <br />
           Please check both inbox and spam folder! <br /><br />';
    }
    else
    {	echo 'Mail can not be sent! Please try again later! <br /><br />';
    }
    unset ($_POST["send"]);
}
?>
<html>
<body>
<head>
<title>Send Email</title>
<script type="text/javascript">
function clearMe()
{	document.getElementById("fl").value='';
	document.getElementById("upload").innerHTML="<input type=\"file\" id=\"fl\">";
}
function cekData()
{	if (formemail.from.value == "")
	{	alert("Please fill in from field!");
		formemail.from.focus();
		return false;
	}
	if (formemail.to.value == "")
	{	alert("Please fill in to field!");
		formemail.to.focus();
		return false;
	}
	if (formemail.subject.value == "")
	{	alert("Please type the subject!");
		formemail.subject.focus();
		return false;
	}
	if (formemail.msg.value == "")
	{	alert("Please type the message!");
		formemail.msg.focus();
		return false;
	}
	if (formemail.problemdetail.value == "")
	{	alert("Problem detail must be filled!");
		formemail.problemdetail.focus();
		return false;
	}
	var filter = new RegExp(
		"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" +
		"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
	if (!filter.test(formemail.to.value) && formemail.to.value != "")
	{	alert("Please enter to with valid email address!");
		formemail.to.focus();
		return false;
	}	   
	else
		return true;   
}
</script>
</head>
<form id="idformemail" name="formemail" method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data" onsubmit="return cekData();">
<table>
<tr><td>From</td><td>:</td><td><input type="text" name="from" id="from" size="54" value="Helpdesk Team <helpdesk@kampushendra.com>"></td></tr>
<tr><td>To</td><td>:</td><td><input type="text" name="to" id="to" size="54"></td></tr>
<tr><td>Subject</td><td>:</td><td><input type="text" name="subject" id="subject" size="54"></td></tr>
<tr><td>Message</td><td>:</td><td><textarea name="msg" rows="4" cols="40"></textarea></td></tr>
<tr><td>Attachment</td><td>:</td><td><input type="file" name="upload" id="fl">
<input type="button" value="Clear" onClick="clearMe()"></td></tr>
<tr><td></td><td></td><td><span id="attach"><input type="submit" value="Submit" id="send" name="send"> </span></td></tr>
</table>
</form>
</body>
</html>

Selamat mencoba, semoga sukses.

Membuat File Log Visitor Website dengan PHP

Log Visitor

Log Visitor

PHP memiliki build-in function untuk membaca dan menulis file. Kita akan gunakan function ini untuk membuat catatan/log pengunjung/visitor website kita dengan coding PHP.

Berikut ini Coding PHP selengkapnya.

<?php
error_reporting(0);
date_default_timezone_set("Asia/Jakarta");
main();
function outDir()
{	$outPath = $outPath.'visitorlog\\';
	if (!file_exists($outPath))
	{ mkdir($outPath,0777) or die("can't make subfolder"); }
	return $outPath;
}

function openfile($path,$createDate)
{	$outFile = $path.$createDate.'.html';
	if (!file_exists($outFile))
	{ $fh = fopen($outFile, 'w') or die("can't open file");
	  initiateoutput($fh,$createDate);
	}
	else
	{ $fh = fopen($outFile, 'a') or die("can't open file");	}
	return $fh;
}
function createoutput($file,$execTime,$url,$ipAddress,$browser)
{	fwrite($file,"<tr><td align='center'>$execTime</td><td>".
        strtoupper($url).
        "</td><td>$ipAddress</td><td>$browser</td></tr>");
	fclose($file);
}

function initiateoutput($fh,$createDate)
{	fwrite($fh,"<html>\n");
	fwrite($fh,"<head><title>Laporan</title></head>\n");
	fwrite($fh,"<body>\n");
	fwrite($fh,"</h1>");
	fwrite($fh,"<table border='1' align='center' valign='center'>\n
                    <caption><h1>Data Pengunjung Website per $createDate</h1>
                    </caption>\n");
	fwrite($fh,"<tr><th width='200' align='center'>Waktu</th>
                    <th width='200' align='center'>Halaman</th>
                    <th width='100' align='center'>IP Address</th>
                    <th width='250' align='center'>Browser</th>\n");
}
function main()
{	$execTime = date('Y-m-d H:i:s');
	$createDate = date('d-M-Y');
	$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	$ipAddress   = gethostbyname( $hostname);
	$browser = $_SERVER['HTTP_USER_AGENT'];
	$path = outDir();
	$file = openfile($path,$createDate);
	createoutput($file,$execTime,$url,$ipAddress,$browser);
	$file = openfile($path,$createDate);
	include "$path"."$createDate".".html";
}
?>

Silakan Anda pelajari setiap baris dari coding tersebut.

Selamat mencoba, semoga berhasil.

Cara Akses Database MySQL dengan PHP

Pada tulisan saya sebelumnya saya telah memberikan cara membuat database web dengan mysql. Jadi saya asumsikan Anda sudah memiliki database “login_student” dan “table_login_student”. Kali ini saya akan berikan coding PHP untuk mengakses database MySQL tersebut.

1. Membuat Koneksi PHP ke MySQL
Ketiklah coding PHP di bawah ini dengan notepad (atau notepad++) lalu simpan dengan nama file “config.php”

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "login_student";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname) 
        or die ('Error connecting to mysql');
?>

2. Membuat Form Insert Data
Ketiklah coding PHP di bawah ini dengan notepad (atau notepad++) lalu simpan dengan nama file “insert.php”

<html>
<head>
<title>Tambah Data</title>
</head>
<body>
<?php
if(isset($_POST['save']))
{  include 'config.php';
   extract($_REQUEST);
   $query=mysqli_query($conn,"insert into tabel_login_student
          SET username='$username', password='$password', level='$level',
          fullname='$fullname', email='$email', Telp='$Telp'")
          or die(mysqli_error($conn));
   if($query)
   {  echo "Data telah tersimpan.";
   }
}
?>
<form action='#' method='post' border='0'>
<table>
<tr><td>Username</td><td><input type='text' name='username' /></td>
</tr>
<tr><td>Password</td><td><input type='text' name='password' /></td>
</tr>
<tr><td>Level</td><td><input type='text' name='level' /></td>
</tr>
<tr><td>Fullname</td><td><input type='text' name='fullname' /></td>
</tr>
<tr><td>Email</td><td><input type='text' name='email' /></td>
</tr>
<tr><td>Telp</td><td><input type='text' name='Telp' /></td>
</tr>
<tr><td></td><td><input type='submit' value='Save' name="save" /></td>
</tr>
</table>
</form>
</body>
</html>

3. Menampilkan Data
Ketiklah coding PHP di bawah ini dengan notepad (atau notepad++) lalu simpan dengan nama file “show_data.php”

<?php
   include 'config.php';
   $sql="select * from tabel_login_student";
   $rs=mysqli_query($conn,$sql) or die($sql.">>".mysqli_error($conn));
   $num=mysqli_num_rows($rs);
   if($num>0){ //check if more than 0 record found
?>
<table border='1'>
<tr>
  <th>Username</th><th>Password</th><th>Level</th><th>Fullname</th><th>Email</th><th>Telp</th>
</tr>
<?php
  while($row=mysqli_fetch_array($rs))
  {  extract($row);
?>
<tr>
  <td><?php echo $username; ?></td>
  <td><?php echo $password; ?></td>
  <td><?php echo $level; ?></td> 
  <td><?php echo $fullname; ?></td>
  <td><?php echo $email; ?></td>
  <td><?php echo $Telp; ?></td>
</tr>
<?php
}
?>
</table>
<?php
} else { echo "Data tidak tersedia."; }
?>

Selanjutnya kita bisa kembangkan coding tersebut dengan membuat aplikasi CRUD (Create, Read, Update, Delete) yang banyak digunakan di aplikasi web.
Selamat mencoba dan semoga sukses.