Saturday, January 21, 2012

Creating a Login Page That Returns to The Last Visited Page in PHP

Today I gonna post a tutorial about how to create a login page which returns to the last visited (refering) page on success.

Usually we see on many websites that when we do a login process, the website redirects to its homepage or account page if the login is successful. Creating this is quite easy. But sometimes we also see some websites (such as YouTube) redirects its user to the last visited page after logging in.

The main idea is quite simple. When a user go to the login page, the page find out the URL where the user comes from (in PHP this can be achieved by checking $_SERVER['HTTP_REFERER'] variable). This information is passed alongside with user credentials (username and password) to the login process page. So when the login succeed, the page can redirect the user to the provided URL.

Okay now let's go into the business.

1. Create some pages.

In this tutorial we are going to make two simple pages that users can browse between them. Let's make the first page:

index.php

<php
// Check session state
session_start();
if($_SESSION['is_logged_in'] == true)
    $logged_in = true;
else
    $logged_in = false;
?>

<h1>This is The First Page</h1>

<a href="page2.php">Go to the second page</a>

<?php if($logged_in) : ?>
    <p>You are logged in.</p>
    <a href="logout.php">Click here to logout</a>
<?php else : ?>
    <a href="login.php">Click here to login</a>
<?php endif; ?>

Note: To simplify the code, the above lines is not a valid HTML document. When making a real pages you should write all the HTML, HEAD, and BODY tags in the correct form

We have two links: login and logout. Either of this links will be displayed based on user's login state. When a user is logged in, the $_SESSION['is_logged_in'] is set to true. The session variable will be described later in this tutorial.

Next we make another page similar to the first one. You can just copy the file and make changes to its title to differentiate the latter from the first one.

page2.php
<php
// Check session state
session_start();
if($_SESSION['is_logged_in'] == true)
    $logged_in = true;
else
    $logged_in = false;
?>

<h1>This is The Second Page</h1>

<a href="index.php">Go to the first page</a>

<?php if($logged_in) : ?>
    <p>You are logged in.</p>
    <a href="logout.php">Click here to logout</a>
<?php else : ?>
    <a href="login.php">Click here to login</a>
<?php endif; ?>

2. The Login Page.

We see that if we click on the "Click here to login" link, it will go to login.php. Now we make a simple login form with just username and password fields. But before that, we first check and get the URL where user comes from and assign it to a variable $redirect_to. We can know the information from $_SERVER['HTTP_REFERER'].

login.php
<?php
// Get the refering page (if unset)
if(!isset($redirect_to))
    $redirect_to = $_SERVER['HTTP_REFERER'];
?>

Okay, then goes the login form:
<h1>Login</h1>

<form action="login_submit.php" method="POST">
    <label>
        Username:<br />
        <input type="text" name="username" value="<?=@$username?>" /><br />
    </label>
    <label>
        Password:<br />
        <input type="password" name="password" /><br />
    </label>
    <input type="submit" value="Login" />
    <input type="hidden" name="redirect_to" value="<?=$redirect_to?>" />
</form>

<p><?=@$error?></p>

Inside the form we put a hidden value named "redirect_to" to pass the URL we get before to login_submit.php which will process the form.

Note: For you who are new to PHP, you can see that I write <?=$redirect_to?> as the value of the hidden field. That is the shorthand version to write PHP code which has the same meaning as <?php echo $redirect_to; ?>. Additionally you can also see an @ symbol before the variable name. This is used to surpress error messages (i.e. if we use/print the variable while it is unset).

3. The Login Process.

When a user clicks Login button, all the above data are sent to login_submit.php. In this file, we check for the username/password pair. If they match then the login is successful and we can go back to the last page. Otherwise the login form is displayed again with an error message.

For this example we will just check that user must enter "admin" as his username and password.

login_submit.php
<?php
// Get form inputs
$username = $_POST['username'];
$password = $_POST['password'];
$redirect_to = $_POST['redirect_to'];

// Check login credentials
if($username == 'admin' && $password == 'admin') {
    // Success
    session_start();
    $_SESSION['is_logged_in'] = true;

    // If the last page is known, redirect to last page,
    // otherwise go to home page.
    if($redirect_to != '')
        header('Location: '.$redirect_to);
    else
        header('Location: index.php');
}
else {
    // When failure, reload the login form
    $error = "Invalid username/password";
    include('login.php');
}
?>

Sometimes $_SERVER['HTTP_REFERER'] (or the $redirect_to variable in this case) may not contain any data. This event may occur when users are directly going to the login page by typing the URL in the address bar, for example. So we still need to check that if $redirect_to is empty, we just go to the homepage (index.php) as usual.

4. Bonus: The Logout Process.

So far, our login page tutorial should be finished here. But it's not complete if we don't also create the logout page. So as a bonus, here's the code for logout.php.

logout.php
<?php
// Get the refering page
$redirect_to = $_SERVER['HTTP_REFERER'];

// Destroy session (logout)
session_start();
session_destroy();

// If the last page is known, redirect to last page,
// otherwise go to home page.
if($redirect_to != '')
    header('Location: '.$redirect_to);
else
    header('Location: index.php');
?>

The easiest way to logout is by destroying the session, so all the data inside $_SESSION will be cleared.

When users logout, we might also want them to return to their last visited page, so there we also check for $redirect_to variable. This goes the same way as the one in login_submit.php file.

Hope this tutorial helps! :)

» Download all the files here.

Wednesday, December 14, 2011

Informasi Firmware Kamera Canon

Mungkin ini sudah bukan hal yang baru lagi untuk pengguna kamera Canon. Tapi tidak ada salahnya jika saya posting di sini. Jika pada ponsel ada "Tombol Khusus" untuk melihat nomor IMEI, data tanggal produksi, versi firmware, jumlah pemakaian dsb. dsb., rupanya di kamera pun ada "Tombol Khusus" tersebut untuk mengetahui versi firmware, jumlah pemotretan, kondisi alat, dan lainnya.

Berikut ini caranya.

Sebelum menekan "Tombol Khusus" ini, pertama-tama buat terlebih dahulu 2 File teks kosong dengan nama "vers.req" dan "ver.req". Simpan file ini di direktori root (tempat terluar) dari kartu memori. Kamera perlu mendeteksi keberadaan salah satu dari file ini (tergantung jenis kamera) untuk mengaktifkan fungsi "Tombol Khusus" tersebut.

Masukkan kartu memori ke kamera. Nyalakan kamera dan masuk ke mode PLAYBACK.

Tahan tombol FUNC/SET lalu tekan tombol DISP. Maka akan muncul keterangan jenis kamera, mode PAL/NTSC, serta versi firmware. Untuk informasi lainnya seperti jumlah pemotretan, informasi lensa, informasi driver dsb, tahan tombol FUNC/SET lalu tekan tombol DISP beberapa kali.

Pada Canon SX120IS, Informasi yang ditayangkan sebagai berikut:

  1. (Semua layar)
    Tipe Kamera
    P-ID & PAL/NTSC

    (Layar 1)
    Firmware Ver
    Tanggal
  2. (Layar 2)
    Adj Ver.
    ZoomLensEror
    Tanggal
  3. (Layar 3)
    Total Shoot
    Zoom Retry Count
    Mecha Condition
  4. (Layar 4)
    Driver Info

Tuesday, November 1, 2011

Seberapa "Berat"-kah Bobot Skripsi Anda?

Kita tahu bahwa skripsi yang dibuat oleh mahasiswa di universitas-universitas sangat beragam baik dari segi topik dan isinya maupun bobotnya. Untuk topik tentu bisa segera diketahui dengan membaca judul dan pengantarnya. Tapi bagaimana cara mengetahui bobot dari skripsi tersebut? Berikut ini adalah salah satu caranya.

Tunggu dulu, bobot yang dimaksud dalam tulisan ini adalah bobot dengan makna tersurat. Jadi bukan mengenai kedalaman pembahasan isinya, tapi bobot yang sama artinya seperti menimbang bobot badan Anda. Atau dengan istilah fisikanya, berapakah massa dari skripsi tersebut?

Apabila merujuk pada aturan format penulisan skripsi di Binus, kertas yang digunakan adalah Quarto (Letter) 80 g/m2. Nah, dari jenis kertas ini sudah dapat diukur bobotnya. 80 g/m2 berarti dalam satu meter persegi (1m × 1m) massanya adalah 80 gram. Jadi untuk kertas Quarto yang berukuran 216 × 279 mm, massa per lembarnya adalah:

(0.216 × 0.279) × 80 = 4.82112 gram / lembar

Misalkan skripsi softcover terdiri dari 500 halaman, maka total massanya menjadi:

500 × 4.82112 = 2410.56 gram = 2.4 kg

Tentu saja nilai di atas hanya perkiraan, karena pada kenyataannya masih ada hal-hal lain yang mempengaruhi, seperti massa tinta dan sampul.

Jika Anda kurang terampil dalam hitung-menghitung, masih ada satu cara lain yang sangat mudah untuk mengetahui bobot skripsi. Mudah saja, cukup ambil satu jilid skripsi dan taruh di atas timbangan sayur. Selesai.

Wednesday, October 19, 2011

Mendapat Kurs Valuta Asing Terkini dengan PHP

Mendapatkan informasi nilai tukar valas (valuta asing) terbaru di internet sebenarnya tidaklah sulit. Ada banyak situs-situs perbankan di Indonesia yang menyediakan informasi kurs terkini, seperti di antaranya:

Mengakses halaman tersebut dari web browser memang mudah. Tetapi masalahnya, bagaimana jika kita sedang membuat sebuah aplikasi web dan ingin mendapatkan data kurs terkini dari situs-situs tersebut untuk diintegrasikan dengan program web.

Karena situs-situs tersebut tidak menyediakan pilihan penyajian informasi dalam format yang programmer-friendly (misalnya JSON atau XML), maka cara yang bisa dilakukan adalah dengan melakukan parsing HTML.

Bagi Anda yang menggunakan PHP, hal ini bisa dilakukan dengan sebuah pustaka PHP untuk mendapatkan data kurs terbaru dari situs-situs perbankan yang terangkum dalam sebuah class KursValas. Unduh file-nya disini.

Cara penggunaannya pun mudah, misalkan kita ingin mendapatkan besaran kurs jual mata uang USD untuk transaksi yang diperoleh dari situs BCA:

<?php

require_once "kursvalas.php";
$kurs = new KursValas("bca", "trx");
echo "1 USD = Rp " . $kurs->get("USD", "sell");
?>


Saat ini KursValas mampu membaca data dari situs BCA, BNI, dan Mandiri.

Beberapa catatan: Karena seluruh informasi kurs ini berasal dari situs eksternal, maka pustaka mungkin bisa menjadi tidak berfungsi sewaktu-waktu jika terjadi perubahan struktur layout halaman di situs tersebut.

KursValas ini menggunakan pustaka simple_html_dom.php yang dibuat oleh S.C. Chen dkk., dirilis dibawah lisensi MIT.

Download KursValas.php
http://static.jar2.net/files-public/scripts/kursvalas-1.3.src.zip

Wednesday, August 17, 2011

Wheel Color Picker 1.2 is Out!

Despite the two months age of the Wheel Color Picker plugin since its first debut, it is already used in various websites across countries. Therefore I am happy to announce the new release of jQuery Wheel Color Picker plugin! This new version adds some new exciting features and fixes:

  • Setting preset value is now supported. This can be achieved either by setting "value" attribute to inputs (e.g. < input class="colorpicker" value="FF0000" />) or adding "color" option when initializing (e.g. $('.colorpicker').wheelColorPicker({ color: "FF0000" }); ).
  • Added "rgb%" (i.e. rgb(100%, 100%, 100%)) and "rgba%" (i.e. rgba(100%, 100%, 100%, 1) ) color formats.
  • The color picker now supports alpha value. If you set color format option to "rgba" or "rgba%", the color picker dialog will come up with additional alpha slider on the right.
  • Fixed a bug that giving undefined reference to rselectedColor error when using rgba format.

Grab the package while it's hot directly from http://plugins.jquery.com/files/jquery.wheelcolorpicker-1.2.0.zip

For an online demonstration and documentation, please visit http://www.jar2.net/projects/jquery-wheelcolorpicker/demo.

There are still things to do to improve this plugin, such as adding HSL color format support, advanced color picker and so on. Let's look forward to have more new useful features implemented on the next release.


    Thursday, June 30, 2011

    Hack Profil FB Dijadikan Online Shop Palsu

    Kepada peselancar internet yang memiliki akun profil di situs-situs jejaring sosial agaknya perlu lebih berhati-hati dalam menjaga dari akses orang-orang yang tidak berhak.

    Baru-baru ini aku menjumpai postingan wall Facebook dari "toko online" yang menjajakan gadget high-end dengan harga sangat miring (mungkin seperti orang yang jualannya ). Ya, masakan Nokia N900 yang harga normalnya Rp 4.900.000,- dibanderol Rp 1.500.000,- dengan "kualitas aseli/bukan replika", demikian juga dengan produk-produk seperti MacBook Pro seharga Rp 6.700.000,-

    Melihat harga-harga yang tidak wajar bikin aku penasaran untuk mengulik profil Facebook tersebut.

    Toko Online Palsu

    Profil "toko online" ini melabel dirinya sebagai toko online ber-SIUP (Surat Ijin Usaha Perdagangan) dan ber-TDP (Tanda Daftar Perusahaan), lengkap dengan foto "toko offline"-nya yang berlokasi di Batam.

    Tapi setelah ditelusuri memang bukan hanya harganya yang tidak wajar, namun masih ada beberapa hal yang tidak wajar. Jika Anda menemukan keganjilan-keganjilan seperti ini, mungkin Anda akan berpendapat bahwa ini adalah toko online palsu alias penipuan.

    Sangat berusaha meyakinkan calon "customer" (baca: korban) untuk percaya.

    Ada pertanyaan yang bisa diajukan, mengapa bisa seseorang begitu rupa berusaha untuk meyakinkan orang untuk percaya? Jawabannya mudah, karena dia tidak bisa dipercaya. Coba Anda bandingkan dengan orang-orang yang Anda hormati. Jika beliau berujar, apakah kita percaya dengan ucapannya, meskipun dia sama sekali tidak berusaha meyakinkan Anda akan kebenaran ucapannya?

    Berusaha meyakinkan "customer"

    Profil pribadi disulap jadi toko dalam sekejap.

    Tidakkah aneh jika seseorang merelakan profil pribadinya--yang mana digunakan untuk bersosialisasi dan berteman pada umumnya--dirombak menjadi sebuah toko online. Hari-hari sebelum "About Me" diubah masih terjadi percakapan dan salam, tetapi setelah itu semua berubah jadi postingan gadget.

    Wall sebelum di-hack (kiriman sebelum "Changed his About Me")
    Wall setelah di-hack. (kiriman setelah "Changed his About Me")

    Kasihan juga yang punya akun, profilnya di-hack di hari ulang tahunnya..

    Alamat URL tidak sesuai dengan nama toko.

    Mungkin kita sudah tidak heran lagi jika melihat URL facebook dari "Toko Jujur" ini sebagai http://www.facebook.com/melinda (nama ini hanya contoh saja).

    Toko berisi konten pribadi.

    Mungkin orang yang me-hack cukup pintar untuk mengubah nama, informasi serta menghapus semua album foto dan menukarnya dengan gambar-gambar "barang" jualan. Tapi karena itu bukan laman miliknya, mungkin dia kurang teliti dengan menyisakan konten-konten yang sifatnya pribadi, seperti notes main bulu ketek ini.

    Toko gadget main bulu ketek?

    No offense ya buat yang profilnya dipakai untuk screenshot di sini. Sebenarnya ada beberapa nama profil dari koneksi Facebook aku yang punya gejala-gejala yang sama. Saran untuk mereka (pemilik sebenarnya) yang profilnya di-hack, sebaiknya segera laporkan kepada pihak penyedia layanan, d.h.i Facebook agar nama baik tidak tercoreng.

    Laporkan penyalahgunaan.

    Menjaga akun online Anda


    Moral dari blog kali ini adalah: jagalah keamanan data pribadi Anda di Internet. Berikut ini ada sedikit tips yang mungkin bermanfaat:
    • Jangan gunakan password yang sama pada beberapa layanan/website. Jika sampai seseorang berhasil membobol password Anda di satu tempat, akun Anda di situs lain masih aman karena memiliki password  yang beda.
    • Logout sehabis menggunakan. Ini sangat penting jika Anda memakai komputer publik, seperti di warnet atau komputer pinjaman.
    • Jangan centang tanda "Tetap masuk", "Ingat saya" atau "Remember me" jika memakai komputer publik. Dengan mencentang tanda ini, akun akan tetap bisa diakses walaupun peramban web ditutup.
    • Hapus history penjelajahan. Setiap halaman yang Anda buka tercatat di komputer. Jika catatan ini tidak dihapus, orang lain bisa menelusuri halaman apa saja yang pernah dibuka dengan menekan Ctrl+H.
      Menu untuk menghapus di tiap browser mungkin tidak sama, tetapi pada pokoknya cari saja menu semacam "Clear browsing history" atau "Clear browser cache" atau "Bersihkan sejarah penjelajahan"

    Saturday, June 11, 2011

    Converting Image to Grayscale with PHP

    As everybody knows, converting images offline into grayscale in GIMP (or probably Photoshop) is just 2 clicks away. But how about converting them on the fly? Anyways, here's a simple steps to convert an image into grayscale with PHP and GD library.

    Getting Started

    Original
    Grayscale
    Let's begin by choosing your image. For this example, I am using a yummy chicken noodle from Solaria restaurant.

    The main idea is to read every pixel's RGB value and convert them using YIQ colorspace conversion matrix. We only need the Y value for the result color.

    So, here's the function to get the Y value from an RGB color:
    <?php
    // Function to get grayscale color from RGB
    function grayscale($color) {
        $r = ($color >> 16) & 0xFF;
        $g = ($color >> 8) & 0xFF;
        $b = $color & 0xFF;
        $yiq = round($r*0.299 + $g*0.587 + $b*0.114);
        return sprintf("0x%02x%02x%02x", $yiq, $yiq, $yiq);
    }
    

    $color is in hexadecimal numbers, for example, a magenta color is 0xADD8E6 in hex. We separate its RGB values using binary SHIFT and AND operators, so we have $r = 0xAD, $g = 0xD8, $b = 0xE6.

    The grayscale value is calculated by adding about 30% red, 59% green, and 11% blue. Don't forget to round the result.

    As we are working in RGB, so we return the color back in RGB value. So 0xADD8E6 becomes 0xCDCDCD.

    Next, change the content type as image:
    header("Content-type: image/jpeg");

    Get the image resolution and load it into $img
    // Image file to be converted
    $file = "mie-ayam.jpg";
    
    // Get image width & height
    list($width, $height) = getimagesize($file);
    
    // Load source image file
    $img = imagecreatefromjpeg($file);

    Now, replace every pixel into grayscale using the function above:
    for($y = 0; $y < $height; $y++) {
        for($x = 0; $x < $width; $x++) {
            $rgb = imagecolorat($img, $x, $y);
            $gray = grayscale($rgb);
            imagesetpixel($img, $x, $y, $gray);
        }
    }

    Finally we output the JPG image and clear memory
    imagejpeg($img);
    imagedestroy($img);

    Download the file (573 bytes)

    http://en.wikipedia.org/wiki/YIQ
    http://www.prosoxi.com/2011/05/05/converting-images-to-grayscale-using-php-and-the-gd-library/