Restrict access to your Apache Virtual Host

Standard

In some case you need to restrict your virtual host site by IP address. Usually the type of site that handle important information such as Administrator site or web-based database administration site (eg : phpMyAdmin) or else. For example the admin site of your website can be accessed only in Office network. This Apache configuration below may helps you.

<VirtualHost *:80>
    DocumentRoot /path/to/website/admin
    ServerName admin.ariawan.web.id

    <Location />
          Order Deny,Allow
          Deny from all
          Allow from 202.204.9.24
    </Location>

</VirtualHost>

The IP address above is your public IP address of your office. Beside <Location>, you also can use the other Apache directive <Directory>.

You can see the complete documentation of configuration sections containers in Apache, that may be suits your need. Here is the link http://httpd.apache.org/docs/current/sections.html

Yup. That’s all.

How to export your MongoDB collections to CSV files

Standard

For some reasons, we might want to export our data in our mongodb collections into csv files. Is it possible? Yes, it is. Mongodb provide a tools called mongoexport which can used to export your data to JSON or CSV files.

Here is the usage example.

mongoexport –db pricebook –collection product_specification –csv –fields “product_id,category_id,specs” -o specs.csv

This operation written above is exporting product_specification collection in pricebook database into specs.csv file with specified fields. If you want to export your data into CSV file you have to specify what fields that you want to exports. If you want to export into JSON file you don’t have to specifiy the fields.

Check the complete mongodb documentation of mongoexport on the link below. All you need to know about mongoexport are there, usage overview and its complete options.

http://docs.mongodb.org/manual/reference/program/mongoexport/

Now, you know how to export your mongodb collections into csv files. What if you have 99 collections? What if in every collections you have more than 100 fields? Exporting it one by one and specifying fields for each collections is bothersome. Sometimes you might want to export all of your collections without specifying field name.

http://drzon.net/export-mongodb-collections-to-csv-without-specifying-fields/

Thanks to drzon and his little bash script. Here is the script.

Hope that helps. Cheers.

 

How to convert foreign chars on Code Igniter

Standard

Working with foreign chars on Code Igniter is super simple. I’ve been working on website with vietnamese language for quite some time. Yes, vietnamese character with their curly accessories on alphabets.

For example if you use slug on your vietnamese language on url you will get “Disallowed Character” error. Another case if you are working with payment gateway, unfortunately they don’t accept charset except UTF-8, eg : The famous PayPal and others.

Enough talks, here i show you how.

First, load the Text Helper, or you can put it on autoload config.

$this->load->helper('text');

After the helper is loaded then here is how you use it. Simply just call this method to convert it.

$string = convert_accented_characters($string);

You can add the character mapping on foreign_chars.php under config directory. Here is the example.

Yes. It is done. Hope this helps. This post is more like bookmark so i know where to look when i need it :P

Simple CRUD web using Nodejs and MongoDB

a simple CRUD web using nodejs (expressjs f/w, hbs templating) and mongodb
Standard
a simple CRUD web using nodejs (expressjs f/w, hbs templating) and mongodb

a simple CRUD web using nodejs (expressjs f/w, hbs templating) and mongodb

In this article, i just want to share my one day experiment with node.js and mongodb. I build a simple web that does CRUD in node.js and save the records to MongoDB. I stupidly built this although this post says that build CRUD in node.js is a bad use case :p

Skip the talks, lets go to the points. I built this on Windows. I need (of course) node.js and mongodb, go to their websites, download and install them to your computer. Once you got them installed then you are ready to code.

Next step is get a HTML template for user interface, if you are LAZY like me just use Bootstrap, from twitter. I need their awesome HTML CSS tables and forms, icons right away. Download and use one of their examples, i am using the fluid layout. User interface? Done.

This is the hardest part (for me), code in node.js. Step one, to make this easier i have to install expressjs. In your app directory type this…

npm install -g express

express “D:/monode-crud” (this is depend on you app directory)

Line one will install expressjs as node modules on your app, and line two will create a directories that expressjs needed. Go to expressjs.com for complete guide.

I don’t like the jade that expressjs used as their default template engine. Instead of using jade, i am installing another node modules called hbs. What is hbs? Hbs is a view engine for express.js. Here is hbs website https://github.com/donpark/hbs. Hbs is basically a handler for Handlebars.js, a Mustache.js-like template engine. Both of them are logic less templates.

npm install hbs

After you are finished installing hbs, then modify your node.js app configurations.

var hbs = require('hbs');
....
....

app.engine('html', require('hbs').__express);
app.set('views', __dirname + '/views/html');
app.set('view engine', 'html');

And then copy all the assets (image, javascript, css files) from bootstrap to “public” directory. Put your .html template under “views” directory.

In order to connect to Mongodb to store the records, i am using node-mongodb-native. There are many other libraries to do this, but IMHO, this is the easiest way to connect node.js and mongodb. Install this via npm as usual.

npm install mongodb

Okay. All done. :)

Check out the complete node.js app and codes at my github page. Here is the repo.

Please drop your comments or questions through this blog or follow me @hadiariawan at twitter. Thanks.

Jquery zFilter – Filtering your HTML table rows

Standard

Pernah punya data dalam tabel yang rownya banyaknya minta ampun dan gak ada fitur searchnya? Nah plugin jquery ini jawabannya… Jquery plugin zFilter untuk mengakomodir hal itu. Plugin jquery buatan @hazmi ini bisa digunakan untuk memfilter row dalam table berdasarkan pencarian.

Cara menggunakan plugin ini cukup mudah, include jquery dan file plugin jquery zfilter, kemudian copy paste code dibawah ini.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><script type="text/javascript" src="jquery.zfilter-0.1.js"></script>
<script type="text/javascript">// <![CDATA[
    (function($) {
        var table = $('#twitter-table');
        var index = 1;
        var input = $('#filter');

        zFilter.setup(input, table, index);

    })(jQuery);

// ]]></script>

Plugin bisa di-download di halaman dibawah ini, lengkap dengan contoh, format tabel dan demo.

http://hadiariawan.web.id/jquery-zfilter/

Happy coding….

CodeIgniter Session Problem

Standard

“Why my user session keep expiring?” “Why CodeIgniter session expires when the page refreshed?

Bagi yang sudah sering menggunakan CI biasanya pernah mengalami masalah session problem ini. Usut punya usut dan cari punya cari, ternyata banyak juga yang mengalami masalah serupa. Di forum CodeIgniter pun ada beberapa thread yang posting masalah ini. Kenapa sessionnya expired terus? Atau malah tidak bekerja dengan semestinya di Internet Explorer versi lawas sedangkan di browser lain tidak masalah.

Banyak yang bilang session class si CI ini unreliable. Well, yes it is. I couldn’t agree more with it. CodeIgniter membuat session class-nya ini tidak menggunakan native session-nya PHP, tetapi CI generate sendiri session data mereka. Alasannya agar session lebih fleksibel bagi developer.

Untuk masalah diatas, ini salah satu workaround-nya. Menggunakan external library yang dibikin oleh mas Dariusz Debowczyk yang cerdas nan brilian. Skrip session class-nya dapat diunduh di tautan berikut (atau di akhir post ini) :

http://codeigniter.com/wiki/Dariusz_Debowczyk%27s_Session_Class

Cara menggunakannya cukup simpel, copy dan paste skrip lalu save di direktori “libraries” dengan nama Session.php. Kemudian tinggal panggil library seperti biasa, $this->load->library(“session”); atau didefinisikan di file config/autoload.php di option library-nya. Problem solved! :)

Menurut posting di thread forum CI, library ini berjalan pada CodeIgniter versi 1 dan 2. Saya sudah coba gunakan dan jalan baik-baik saja di versi 2. Di bawah ini skrip session class mas Darius saya kutip untuk mempermudah copy dan pastenya.

</span>
<pre><!--?php  if (!defined('BASEPATH')) exit('No direct script access allowed'); /?-->  makes dw cs4 happy

/**
* Session class using native PHP session features and hardened against session fixation.
*
* @package     CodeIgniter
* @subpackage  Libraries
* @category    Sessions
* @author      Dariusz Debowczyk, Matthew Toledo
* @link        http://www.philsbury.co.uk/index.php/blog/code-igniter-sessions/
*/
class CI_Session {

    var $flashdata_key     = 'flash'; // prefix for "flash" variables (eg. flash:new:message)

    function CI_Session()
    {
        $this->object =& get_instance();
        log_message('debug', "Native_session Class Initialized");
        $this->_sess_run();
    }

    /**
    * Regenerates session id
    */
    function regenerate_id()
    {
        // copy old session data, including its id
        $old_session_id = session_id();
        $old_session_data = $_SESSION;

        // regenerate session id and store it
        session_regenerate_id();
        $new_session_id = session_id();

        // switch to the old session and destroy its storage
        session_id($old_session_id);
        session_destroy();

        // switch back to the new session id and send the cookie
        session_id($new_session_id);
        session_start();

        // restore the old session data into the new session
        $_SESSION = $old_session_data;

        // update the session creation time
        $_SESSION['regenerated'] = time();

        // session_write_close() patch based on this thread
        // http://www.codeigniter.com/forums/viewthread/1624/
        // there is a question mark ?? as to side affects

        // end the current session and store session data.
        session_write_close();
    }

    /**
    * Destroys the session and erases session storage
    */
    function destroy()
    {
        unset($_SESSION);
        if ( isset( $_COOKIE[session_name()] ) )
        {
            setcookie(session_name(), '', time()-42000, '/');
        }
        session_destroy();
    }

    /**
    * Alias for destroy(), makes 1.7.2 happy.
    */
    function sess_destroy()
    {
        $this->destroy();
    }

    /**
    * Reads given session attribute value
    */
    function userdata($item)
    {
        if($item == 'session_id'){ //added for backward-compatibility
            return session_id();
        }else{
            return ( ! isset($_SESSION[$item])) ? false : $_SESSION[$item];
        }
    }

    /**
    * Sets session attributes to the given values
    */
    function set_userdata($newdata = array(), $newval = '')
    {
        if (is_string($newdata))
        {
            $newdata = array($newdata => $newval);
        }

        if (count($newdata) > 0)
        {
            foreach ($newdata as $key => $val)
            {
                $_SESSION[$key] = $val;
            }
        }
    }

    /**
    * Erases given session attributes
    */
    function unset_userdata($newdata = array())
    {
        if (is_string($newdata))
        {
            $newdata = array($newdata => '');
        }

        if (count($newdata) > 0)
        {
            foreach ($newdata as $key => $val)
            {
                unset($_SESSION[$key]);
            }
        }
    }

    /**
    * Starts up the session system for current request
    */
    function _sess_run()
    {
        session_start();

        $session_id_ttl = $this->object->config->item('sess_expiration');

        if (is_numeric($session_id_ttl))
        {
            if ($session_id_ttl > 0)
            {
                $this->session_id_ttl = $this->object->config->item('sess_expiration');
            }
            else
            {
                $this->session_id_ttl = (60*60*24*365*2);
            }
        }

        // check if session id needs regeneration
        if ( $this->_session_id_expired() )
        {
            // regenerate session id (session data stays the
            // same, but old session storage is destroyed)
            $this->regenerate_id();
        }

        // delete old flashdata (from last request)
        $this->_flashdata_sweep();

        // mark all new flashdata as old (data will be deleted before next request)
        $this->_flashdata_mark();
    }

    /**
    * Checks if session has expired
    */
    function _session_id_expired()
    {
        if ( !isset( $_SESSION['regenerated'] ) )
        {
            $_SESSION['regenerated'] = time();
            return false;
        }

        $expiry_time = time() - $this->session_id_ttl;

        if ( $_SESSION['regenerated']  $newval);
        }

        if (count($newdata) > 0)
        {
            foreach ($newdata as $key => $val)
            {
                $flashdata_key = $this->flashdata_key.':new:'.$key;
                $this->set_userdata($flashdata_key, $val);
            }
        }
    }

    /**
    * Keeps existing "flash" data available to next request.
    */
    function keep_flashdata($key)
    {
        $old_flashdata_key = $this->flashdata_key.':old:'.$key;
        $value = $this->userdata($old_flashdata_key);

        $new_flashdata_key = $this->flashdata_key.':new:'.$key;
        $this->set_userdata($new_flashdata_key, $value);
    }

    /**
    * Returns "flash" data for the given key.
    */
    function flashdata($key)
    {
        $flashdata_key = $this->flashdata_key.':old:'.$key;
        return $this->userdata($flashdata_key);
    }

    /**
    * PRIVATE: Internal method - marks "flash" session attributes as 'old'
    */
    function _flashdata_mark()
    {
        foreach ($_SESSION as $name => $value)
        {
            $parts = explode(':new:', $name);
            if (is_array($parts) && count($parts) == 2)
            {
                $new_name = $this->flashdata_key.':old:'.$parts[1];
                $this->set_userdata($new_name, $value);
                $this->unset_userdata($name);
            }
        }
    }

    /**
    * PRIVATE: Internal method - removes "flash" session marked as 'old'
    */
    function _flashdata_sweep()
    {
        foreach ($_SESSION as $name => $value)
        {
            $parts = explode(':old:', $name);
            if (is_array($parts) && count($parts) == 2 && $parts[0] == $this->flashdata_key)
            {
                $this->unset_userdata($name);
            }
        }
    }
} 

I hope this post helps you. Have a nice weekend :)

PHP: RSS Yahoo Weather Parser

Standard

Yahoo! Weather menyediakan informasi cuaca hampir semua lokasi di dunia. Informasi cuaca ini bisa diambil melalui RSS yang disediakan oleh Yahoo! Contohnya, informasi cuaca di kota Jakarta, bisa diakses di URL berikut :

http://weather.yahooapis.com/forecastrss?p=IDXX0022&u=c

Gmana cara ngambil datanya? untuk pengguna bahasa pemrograman PHP ini dia contoh kodenya.

function yahooWeatherParser($source) {

//$source = "http://weather.yahooapis.com/forecastrss?p=IDXX0022&amp;u=c";
$strXml = @file_get_contents($source);
if($strXml == false) return false;

$objRss = simplexml_load_string($strXml);

$objWeather = new SimpleXMLElement($strXml);
$weather['condition'] = $objWeather->xpath("//yweather:condition");
$weather['location'] = $objWeather->xpath("//yweather:location");
$weather['units'] = $objWeather->xpath("//yweather:units");
$weather['wind'] = $objWeather->xpath("//yweather:wind");
$weather['atmosphere'] = $objWeather->xpath("//yweather:atmosphere");
$weather['astronomy'] = $objWeather->xpath("//yweather:astronomy");
$weather['forecast'] = $objWeather->xpath("//yweather:forecast");
$weather['description'] =  $objRss->channel->item->description;

return $weather;
}

Gimana cara pakenya? gini ceritanya…

print_r(yahooWeatherParser('http://weather.yahooapis.com/forecastrss?p=IDXX0022&amp;u=c'));

Sekilas PHP dan MongoDB

Standard

Posting kali ini sekedar sharing percobaan menggunakan PHP dengan MongoDB. Apa itu MongoDB? MongoDB adalah document-based database server. MongoDB ini open source dibangun dengan bahasa pemrograman c++. Kata wikipedia, MongoDB ini scalable, high-performance, schema-free, web-scale. Isi dari MongoDB ini adalah koleksi dari dokumen – dokumen JSON-like. Kira – kira isinya begini…

  {
       "username" : "bob",
       "address" : {
           "street" : "123 Main Street",
           "city" : "Springfield",
           "state" : "NY"
       }
   }

Di bawah ini ada slide presentasi yang sempat dibuat dari hasil coba – coba PHP dan MongoDB. Apa? Kenapa? dan Bagaimananya MongoDB silahkan browsing – browsing sendiri ya.. :)

View more presentations from Hadi Ariawan.

Note :

Articles to read related to MongoDB and PHP.

 

  • http://www.mongodb.org/display/DOCS/Introduction

Last.fm Scrobbler di Android Phone

Standard
Last.fm Scrobbler for Android

Last.fm Scrobbler for Android

Buat yang seneng denger musik pasti sudah gak asing lagi dengan last.fm ini. Situs social networking khusus musik ini selain gudang dan koleksi informasi tentang musik, band, album dan lain-lain, last.fm ini juga memungkinkan kita untuk mengupload lagu-lagu yang kita dengerin di komputer kita.

Caranya? Tentunya register last.fm dulu, kemudian download last.fm scrobbler ke komputer kita. Scrobbler last.fm ini otomatis akan mendeteksi music player yang ada dan terinstall di komputer kita dan merekomendasikan untuk download plugin untuk music player kita. iTunes, Windows Media Player, WinAmp ada semua. Setelah semua diinstall, tiap kita dengerin lagu, otomatis akan “disetor” ke last.fm dan akan muncul di bagian “Recent Listened Tracks” di profile kita.

Ha? blom ngeuh juga? coba liat profile last.fm saya di http://www.last.fm/user/hadiariawan pasti ngerti. Disitu infonya lengkap. Top Artists, Music Library, Top Tracks dan lain lain. kalo statistik saya begini 69090 plays since 8 Jan 2009.

Nah.. sekarang gmana kalo kita lagi di perjanalan, di mobil, di kereta yang notabene hampir enggak mungkin tenteng komputer atau leptop dengan koneksi internet kan? Biasanya kalo kondisinya begitu kita denger lagu dari portable music player, bisa iPod atau handphone. Kali ini yang dibahas hanya untuk pengguna android device saja.

Untuk android phone/device pertama kali adalah cari music playernya dulu. Music player yang saya gunakan adalah MixZing. Overall MixZing ini cukup bagus, ada auto finder Album Cover-nya asal ID3Tag nya komplit Mixzing ini otomatis mencari dan mendownload cover album track yang sedang disetel. Bisa masukin lirik tiap lagu juga kalo ga salah, oke.. cukup bahas Mixzing, bisa buat satu post sendiri ini nantinya. Begini kira-kira tampilan mixzing…

MixZing Music Player for Android

MixZing Music Player for Android Image From : http://www.mixzing.com/android.html

Kedua, gmana cara integrasi mixzing ini dengan last.fm scrobblernya. Di menu option mixzing ini ada last.fm intergrasinya, kalo ga salah kalo di klik otomatis pergi ke market dan rekomendasinya adalah Scrobble Droid. Dowload Scrobble droid dari market, setelah selesai download dan install scrobble droid lalu masukkan username dan password last.fm kamu. Kira – kira tampilan scrobble droid begini nih…

Scrobble Droid

Scrobble Droid Image from : http://code.google.com/p/scrobbledroid/

Oke.. beres.. sekarang waktu dengerin lagu dari mixzing di jalan, di mobil atau di kereta, otomatis lagu yang lagi didengerin “disetor” ke last.fm. Kalo lagi ga dapet sinyal atau lagi ga aktif koneksi internet dari android phone nya, lagu yang didengerin lagi disimpen dulu di lokal android phone, kemudian bisa “disetor” manual dengan cara buka aplikasi Scrobble Droid-nya dan klik tombol “Scrobble” di paling bawah.

Keren kan?! teknologi sekarang memang canggih… #ngok (banana_rock)

http://www.last.fm/user/hadiariawan

Installing Zend Optimizer on XAMPP

Standard

Secara default instalasi XAMPP di Windows tidak menyertakan Zend Optimizer, tapi pada umumnya peyedia hosting sudah terinstall Zend Optimizer. Berikut ini langkah – langkah instalasi Zend Optimizer untuk XAMPP di Windows. Versi XAMPP yang digunakan saat post ini ditulis adalah XAMPP 1.7.1.

Direktori instalasi XAMPP yang digunakan ada di D: ( D:\xampp\ )

1. Download Zend Optimizer di website zend.com.

Zend Optimizer bisa di download di http://www.zend.com/en/products/guard/downloads. Tersedia versi MacOS, Linux dan Windows. Download Zend Optimizer for Windows (saat post ini ditulis versi Zend Optimizer 3.3.3)

2. Execute ZendOptimizer-3.3.3-Windows-i386.exe

Pastikan apache/web server dalam keadaan tidak aktif sebelum mulai proses instalasi. Pilih web server yang digunakan, untuk XAMPP 1.7.1 adalah Apache 2.x.x.

Saat proses instalasi ini berjalan, anda akan diberikan 3 kali pertanyaan direktori.

  • Lokasi instalasi Zend Optimizer (C:\Program Files\…..)
    • secara default installer akan menawarkan di C:\Program Files\… Zend Optimizer
  • Lokasi php.ini
    • ubah lokasinya sesuai dengan instalasi xampp, dalam kasus ini lokasi xampp yang digunakan ada di direktori D:\ maka lokasinya adalah D:\xampp\php\
  • Lokasi apache
    • ubah lokasinya sesuai dengan instalasi xampp, dalam kasus ini lokasi xampp yang digunakan ada di direktori D:\ maka lokasinya adalah D:\xampp\apache\

3. Cek phpinfo()

Sebenarnya proses instalasi sudah selesai, Zend Optimizer sudah terinstall di XAMPP. Periksa phpinfo untuk memastikan bahwa Zend Optimizer telah terinstall dengan baik dan benar. Jika sudah terinstall maka akan ada bagian seperti gambar di bawah ini.

Zend Optimizer (phpinfo)

Zend Optimizer (phpinfo)

Setelah selesai instalasi, pastikan option Zend Loader : enabled. Jika option Zend Loader masih disabled, ubahlah setting di file php.ini. Cari dan ubah option zend_optimizer.enable_loader dari 0 ke 1. Contoh lihat gambar di bawah ini.

Zend Optimizer (php.ini)

Zend Optimizer (php.ini)

Lalu test dengan menjalankan aplikasi yang membutuhkan Zend Optimizer. That’s it! It’s Done! ;)

Note:

Sorry, tidak sempat capture pada saat proses instalasi.