Welcome to Abdul Malik Ikhsan's Blog

Practical Regex 3: Using Nested Negative Lookahead

Posted in regex, tips and tricks by samsonasik on February 18, 2022

So, you need to verify a statement, that in the statement, something has NOT followed with other thing, except continue with another thing, for example:

I like foo                 << - not allowed
I like fooSomeRandomString << - not allowed
I like food                << - allowed
I like football            << - allowed
I like drawing             << - allowed
I dislike drawing          << - not allowed

First, let’s create a regex to make “I like” not followed with “foo” with Negative Lookahead “(?!foo)”:

I like (?!foo)[^ ]+

Above regex will match only for “I like drawing”, ref https://regex101.com/r/hAsvYH/1,

Important note:

I used caret for negation character class [^ ] for not space just to ensure it exactly has word found next with non space after collection of character so we can see the result of next word.

Next, continue with another requirement, except “food” and “football”, so we make another Negative Lookahead inside Negative Lookahead “(?!foo(?!d|tball))”:

I like (?!foo(?!d|tball))[^ ]+

Above regex will verify next followed with “foo” is allowed if next of “foo” is “d” or “tball”, so it will matches:

I like food
I like football
I like drawing

ref https://regex101.com/r/hAsvYH/2

Next, how to get “food”, “footbal”, and “drawing”? You can use “Named Capture Group” that cover “Nested Negative Lookahead + “character class [^ ]+” so the word next will be included as a “Named Capture Group”, like the following:

I like (?<like>(?!foo(?!d|tball))[^ ]+)

Above, the word result is captured with named “like”, ref https://regex101.com/r/hAsvYH/3

Let’s use real code to get it, for example, with PHP:

$text = <<<TEXT
I like foo                 << - not allowed
I like fooSomeRandomString << - not allowed
I like food                << - allowed
I like football            << - allowed
I like drawing             << - allowed
I dislike drawing          << - not allowed
TEXT;

$pattern = '#I like (?<like>(?!foo(?!d|tball))[^ ]+)#';
preg_match_all($pattern, $text, $matches);

foreach($matches['like'] as $like) {
    echo $like . PHP_EOL;
}

Ref https://3v4l.org/R7TfC

That’s it 😉

References:

Practical Regex 2: Using Named Backreference in Positive Lookahead

Posted in regex, tips and tricks by samsonasik on September 15, 2021

When we have the following namespaced classname value:

App\Domain\Foo\FooRepository

and our task is to get “Foo” value as Domain group with the criteria:

  • must have App\Domain\ prefix
  • must have \$Domain name + “Repository” suffix which $Domain must match previous sub-namespace, on this case, “Foo”

we can use the following regex with Positive Lookbehind to filter prefix and Positive Lookahead to filter suffix:

(?<=App\\Domain\\)(?<Domain>[A-Z][a-z]{1,})(?=\\\1Repository)

Above, we find $Domain with App\Domain\ before it with Positive Lookbehind, and $DomainRepository after it with Positive Lookahead.

We are using backreference with \1 to match the exact same text of the first capturing group. If you code in PHP, you can do like this:

$pattern   = '#(?<=App\\\\Domain\\\\)(?<Domain>[A-Z][a-z]{1,})(?=\\\\\1Repository)#';
$className = 'App\Domain\Foo\FooRepository';

preg_match($pattern, $className, $matches);
if ($matches !== []) {
    echo $matches['Domain'];
}

What if the code is getting more complex, like in my previous post for named capturing group, you need to remember the numbered index! To handle it, you can use named backreference for it, so the regex will be:

(?<=App\\Domain\\)(?<Domain>[A-Z][a-z]{1,})(?=\\\k<Domain>Repository)

Now, you are exactly know what backrefence reference to. If you code in PHP, you can do like this:

$pattern   = '#(?<=App\\\\Domain\\\\)(?<Domain>[A-Z][a-z]{1,})(?=\\\\\k<Domain>Repository)#';
$className = 'App\Domain\Foo\FooRepository';

preg_match($pattern, $className, $matches);
if ($matches !== []) {
    echo $matches['Domain'];
}

That’s it 😉

Ref: https://www.regular-expressions.info/backref.html

Practical Regex 1: Using Named Capturing Groups

Posted in regex, tips and tricks by samsonasik on September 3, 2021

Still using numbered group of capture value in Regex? You may forget, or the index changed if the requirement changed. For example, you want to get a csrf value from a form field with the following regex example:

name="csrf" value="(.{32})"

For input field csrf with 32 chars value “4X0ZfDKr71KHCec7SOkoJ5onq1PTCN3v”, you want to get the value, you will need to get index 1 for it with PHP:

<?php

$pattern = '#name="csrf" value="(.{32})"#';
$content = <<<'HTML_CONTENT'
<form>
    <input type="hidden" name="csrf" value="4X0ZfDKr71KHCec7SOkoJ5onq1PTCN3v" />
    <input type="submit" />
</form>
HTML_CONTENT;

preg_match($pattern, $content, $matches);
if ($matches !== []) {
    echo $matches[1];
}

To handle the possible forgotten index or changed index that can create a bug, you can use named capturing groups, so you can change to:

name="csrf" value="(?<csrf_value>.{32})"

Now, you can get it easily:

<?php

$pattern = '#name="csrf" value="(?<csrf_value>.{32})"#';
$content = <<<'HTML_CONTENT'
<form>
    <input type="hidden" name="csrf" value="4X0ZfDKr71KHCec7SOkoJ5onq1PTCN3v" />
    <input type="submit" />
</form>
HTML_CONTENT;

preg_match($pattern, $content, $matches);
if ($matches !== []) {
    echo $matches['csrf_value'];
}

That’s it 😉

Ref: https://www.regular-expressions.info/named.html

Tinify : Resize your image without reduce quality

Posted in php, Teknologi, tips and tricks by samsonasik on February 3, 2019

I tried some client library services for my project to resize images. They resized images correctly, however, they made the images quality slightly reduced. Until my client suggested me to try Tinify API service, that the API key I can just use, and it works pretty well.

The Tinify provide free 500 compresions per-month if you need to try. You can upgrade to paid account if you need more. To register, you can go to https://tinypng.com/developers and got the following page and fill your name and email and click “Get your API key”:

You can then check your email to get the link and be redirected to the dashboard page with information of your API key and how many compressions left for current month:

There are libraries for different languages, for example, if you are using PHP, you can use tinify-php that you can require via composer in your project by run:

$ composer require tinify/tinify

Once required, you can do :

include 'vendor/autoload.php';

\Tinify\setKey('YOUR_API_KEY'); // fill with your API key

$source = \Tinify\fromFile('/path/to/file.png'); // source file
$resized = $source->resize(array(
    'method' => 'scale',
    'width'  => 500,
));
$resized->toFile('target-thumbnail.png'); // target file

For complete reference, you can look at https://tinypng.com/developers/reference/php . That’s it!

Rsync : Synchronize local with shared hosting

Posted in Teknologi, tips and tricks by samsonasik on January 26, 2013

rsyncAs web developer, We already realize that we are lazy. Our client is often only have shared hosting, not dedicated server that we can install version control which simplify push and pull. We often forgot to upload some file we changed/added in local to shared hosting, and it make web is not run properly in shared hosting.  The solution is to use rsync in local PC.  Rsync is a file transfer program for Unix systems. rsync uses the ‘rsync algorithm’ which provides a very fast method for bringing remote files into sync. An important feature of rsync not found in most similar programs/protocols is that the mirroring takes place with only one transmission in each direction. Rsync can copy or display directory contents and copy files, optionally using compression and recursion.
So, you need to know the step to do this :
1. Go to your Cpanel
2. Click Ftp Account
Screen Shot 2013-01-26 at 4.36.40 PM
3. Click Configure FTP Client in your desired user
Screen Shot 2013-01-26 at 4.39.14 PM

And see the SFTP Port. Use the port to in rsync port target transfer.
4. Start syncing…

cd ~/www && rsync -timeout=50000 -av --exclude ".git" --exclude ".gitignore" --exclude "wp-config.php"  wordpress_local_dev/ -e "ssh -p 2223" yourremoteserveruser@yourdomain.com:/home/yourremoteserveruser/public_html/

The option –exclude will exclude unneeded to sync.
The option -timeout is what second to be connection to timeout.
And you will see the following ( just updated / added file will be uploaded ) :

5. Done !

References :
Image : http://www.haykranen.nl/wp-content/uploads/2008/05/timemachine.jpg
Source :
1. http://mike-hostetler.com/blog/2007/12/08/rsync-non-standard-ssh-port/
2. http://en.wikipedia.org/wiki/Rsync

WordPress – Create Your Own WordPress Plugin

Posted in tips and tricks, Tutorial PHP by samsonasik on January 30, 2011

WordPress adalah salah satu Open Source CMS yang ramai dipakai saat ini. WordPress mempunyai ribuan plugin yg tersedia dan siap pakai, tinggal unduh, dan tempel. Hanya saja, tentu kita juga sepakat, kalau kebutuhan manusia itu tidak terbatas. Nah, WordPress mempersilakan kita untuk membuat plugin sendiri untuk kebutuhan kita tersebut.

Saya akan mencoba memberi contoh pembuatan plugin sederhana bernama my_plugin. Pertama, kita buat dulu bundle plugin-nya, sederhana saja, kita buat folder bernama my_plugin dan di dalamnya terdapat file my_plugin.php seperti gambar berikut :

Nah, kalau sudah, kita edit file my_plugin.php, beri header comment seperti berikut :

<?php
/*
Plugin Name: My_plugin
Plugin URI: https://samsonasik.wordpress.com
Description: Example purpose
Version: 1.0
License: GPLv2
Author: Abdul Malik Ikhsan
Author URI: https://samsonasik.wordpress.com
*/
?>

Kalau sudah, kita compress ke zip deh folder kita tadi, lalu kita upload di admin CMS WP kita di menu Plugins -> Add New seperti gambar berikut :

Klik Install Now, dan activate setelah install selesai. Nah, sekarang kita punya plugin baru yg terlihat di daftar plugin WP kita, seperti berikut :

Wokeh, saatnya mengedit plugin kita agar bisa dipakai. Kita edit file my_plugin.php kita yang sudah terupload di folder wp-content/plugins/my_plugin :

<?php
/*
Plugin Name: My_plugin
Plugin URI: https://samsonasik.wordpress.com
Description: Example purpose
Version: 1.0
License: GPLv2
Author: Abdul Malik Ikhsan
Author URI: https://samsonasik.wordpress.com
*/
function showsomethingbymyplugin()
{
 echo "this is something rockin' created at ".date('Y-m-d H:i:s')." baby \m/ ";
}

//add shortcode untuk menambahkan shortcode ketika hendak dipanggil di posting
add_shortcode('my_plugin_something', 'showsomethingbymyplugin');
?>

Kalau sudah, cekidot deh kita panggil di posting-an kita atau di salah satu halaman wordpress kita :

Ok, terakhir, kita cek deh di halaman kita, kalau berhasil maka akan tampil seperti berikut :


Referensi  :
http://codex.wordpress.org/Plugins
http://codex.wordpress.org/Writing_a_Plugin
http://en.wikipedia.org/wiki/Wordpress
http://farm5.static.flickr.com/4129/5036291025_2ea3a4c5b6_z.jpg

PHPDocumentor : The Complete Documentation Solution for PHP

Posted in Teknologi, tips and tricks, Tutorial PHP by samsonasik on June 26, 2010

Menulis dokumentasi yang baik sangat penting bagi keberhasilan setiap proyek perangkat lunak. Kualitas dokumentasi bahkan bisa lebih penting daripada kualitas kode itu sendiri.  Kebanyakan programmer paling malas untuk membuat dokumentasi dengan alasan tidak mempunyai waktu yang cukup untuk membuat dokumentasi yang baik. Nah, apa yang terjadi ketika terjadi pengembangan perangkat lunak ? Programmer itu sendiri kesulitan untuk menerjemahkan kode programnya sendiri.   Nah, yang lebih jadi masalah apabila programmernya ganti. Kebayang ga apa yg akan terjadi ? He.he.he.he…

phpDocumentor dirancang untuk memudahkan untuk membuat dokumentasi.  Untuk menginstall phpDocumentor, pertama kita harus mempunyai PEAR , cara installnya silakan dibaca sendiri. Setelah itu kita run command :

pear install PhpDocumentor

Kalau sudah, kita buat deh simulasi contoh pembuatan dokumentasinya. Kita buat folder dan kita buat file-file php kita, contoh kita punya 2 file di satu folder, misal di D:\Zend\Apache2\htdocs\tutwordpress\testwillbedoc , dan kita beri nama WordPress1.php dan WordPress2.php. phpDocumentor mempunyai tag-tag yang berawalan dengan ‘@’ yang merupakan deskripsi program.

<?php
/**
 * This class is Parent of WordPress2
 * @author Abdul Malik Ikhsan
 * @filesource WordPress1.php
 * @version 1.0
 */
class WordPress1
{
 /**
 * a static variable
 * @static
 */
 public static $astaticvar = 0;

 /**
 * @todo initialize all func needed
 * @access public
 * @param String $param1
 * @param String $param2
 */
 public function WordPress1($param1,$param2)
 {
 //initialize all func needed
 }
}
?>

Kemudian file ke 2

<?php
/**
 * This class is Child of WordPress1
 * @author Abdul Malik Ikhsan
 * @filesource WordPress2.php
 * @version 1.0
 */

require_once 'Wordpress1.php';
class WordPress2 extends WordPress1
{
 /**
 * @todo initialize all func needed
 * @access public
 * @param String $param1
 * @param String $param2
 * @see WordPress1 Constructor
 */
 public function WordPress2($param1,$param2)
 {
 //initialize all func needed
 parent::Wordpress1($param1,$param2);
 }

 private function staticFunc()
 {

 }

 public function callerFunc()
 {

 }
}
?>

Kalau sudah, coba deh run di command line, seperti berikut :

phpdoc -o HTML:frames:phpedit -d D:\Zend\Apache2\htdocs\tutwordpress\testwillbedoc -s -t D:\Zend\Apache2\htdocs\tutwordpress\docs

Ok, kalau berhasil, maka akan terbentuk folder di D:\Zend\Apache2\htdocs\tutwordpress\ dan di dalamnya ada file-file HTML yang tergenerate seperti gambar berikut :

Nah, Coba kita klik file index.html-nya, maka akan tampil seperti berikut :

jQuery – Using JSON for data transfers

Posted in Javascript, tips and tricks, Tutorial PHP by samsonasik on April 14, 2010

JSON (dilafalkan “Jason”),  adalah singkatan dari JavaScript Object Notation (bahasa Indonesia: notasi objek JavaScript), adalah suatu format ringkas pertukaran data komputer. Formatnya berbasis teks dan terbaca-manusia serta digunakan untuk merepresentasikan struktur data sederhana dan larik asosiatif (disebut objek).

Penggunaan JSON pada pertukaran transfer data, terutama ketika kita menggunakan AJAX, sangatlah bermanfaat, tapi tentu saja alangkah lebih baiknya, jika selain memanfaatkan JSON secara murni, kita juga tahu tools-tools yang bisa digunakan agar pemanfaatan JSON bisa lebih cepat. Salah satu Tools yang bisa digunakan adalah Javascript Library yang tentu sudah tidak asing lagi bagi kita semua, yaitu jQuery.

Ok, saya akan memberikan satu contoh sederhana pemanfaatan JSON menggunakan jQuery javascript library dan PHP.
Pertama, kita siapkan file2 yang dibutuhkan, seperti gambar berikut:

Keterangan :
1. frmjson.html     : file view kita.
2. getjson.php       : serverside script untuk menangkap data yang ditransfer.
3. jquery-1.4.2.js : Javascript library-nya.
————
Now, let’s coding :
1. frmjson.html

<!-- frmjson.html -->
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
 //closure button berid = "setter" diklik...
 $("#setter").click(function(){
 $.post("getjson.php",{
 nama : $("#nama").val(),
 alamat : $("#alamat").val()
 }, function(data){
 //jika response telah berhasil... (set label...)
 $("#lblgetattr").html(data.nama+" beralamat di "+data.alamat);
 },"json");
 });
 });
</script>
Nama : <input type="text" id="nama"> <br>
Alamat : <input type="text" id="alamat"> <br>
<input type="button" value="SetAtribute" id="setter">
<br>
Atribut yang sudah terset adalah : <label id="lblgetattr"></label>

2. getjson.php :

<?php
 $data['nama'] =  strtoupper($_POST['nama']);
 $data['alamat'] = $_POST['alamat'];

 echo json_encode($data);

3. jQuery-1.4.2.js (Bisa didownload di situs http://jquery.com )

Sebelum button dengan id =”setter” diklik, maka akan tampil halaman seperti ini :

Dari gambar di atas, kita belum melihat respon apa2 karena button dengan id =”setter” belum kita klik, jika kita isi nama dan alamat, kemudian kita klik button dengan id=”setter” tersebut, maka akan tampil seperti berikut :

Gambar di atas menunjukkkan dari sisi background, javascript mengirimkan request ke getjson.php , kemudian response tersebut dikirim ke browser, dan ditampilkan di view browser.

Asik kan yach ? welcome to RIA world 🙂
———————–

Referensi :
http://id.wikipedia.org/wiki/JSON
http://json.org/
http://jquery.com

Tagged with: ,

CodeIgniter modular with separating your own module and core CodeIgniter Application Framework

Posted in tips and tricks, Tutorial PHP by samsonasik on March 5, 2010

Cie, judulnya in English lagih, 😀 …
Langsung ajah yach (halah mulai dah alay, xi.xi.xi..), pada tulisan saya kali ini, saya akan membahas tentang codeIgniter modular dengan memisahkan module-module yang kita buat dan core CodeIgniter Application Framework. Pertama, yang harus kita tahu, codeIgniter mode clean-install tidak menyediakan sistem modular, hal ini tentu sangat membuat capek. Tentang pembandingan aplikasi modular dan tidak modular dapat di lihat di postingan saya yang sebelumnya untuk Zend Framework. Sebenarnya, kalau saya lihat, memang modular aplication membuat performa aplikasi menjadi sedikit lebih lambat, tapi tentu toh kita akan ambil resiko itu untuk sesuatu yang lebih menjanjikan, yaitu efisiensi dan keteraturan yang akan kita dapatkan nantinya.

Hal pertama, kita download dulu extension dari codeIgniter wiki : CodeIgniter modular extension ,  ( dokumentasi bisa dilihat di sini) , nah setelah kita download file .zip -nya, kita extract saja ke dalam folder system/application/libraries , setelah itu, let’s setting directory structure menjadi seperti ini :

Dari gambar di atas, terlihat saya membuat dua module, yaitu mod_default dan mod_sample.
Ok, kalau sudah, kita coba cut (CTRL + X) controllers, models, dan views di folder system/application kita (Jangan takut error !!!, namanya juga belajar kan 🙂 ).
Kalau sudah, kita coba cut (CTRL + X) file index.php yang ada di folder codeIgniter kita yang seharusnya sejajar dengan folder system ke dalam folder public yang baru saja kita buat. Setelah itu, kita edit file index.php kita tersebut di bagian SET THE SERVER PATH :

/*
|---------------------------------------------------------------
| SET THE SERVER PATH
|---------------------------------------------------------------
|
| Let's attempt to determine the full-server path to the "system"
| folder in order to reduce the possibility of path problems.
| Note: We only attempt this if the user hasn't specified a
| full server path.
|
*/
if (strpos($system_folder, '/') === FALSE)
{
 if (function_exists('realpath') AND @realpath(dirname(__FILE__)) !== FALSE)
 {
 $system_folder = realpath(dirname(__FILE__)).'/../'.$system_folder;
 }
}
else
{
 // Swap directory separators to Unix style for consistency
 $system_folder = str_replace("\\", "/", $system_folder);
}

Lihat pada bagian $system_folder = realpath(dirname(__FILE__)).’/../’.$system_folder; yang merujuk ke folder system yang sejajar folder public, karena require nya diambil dari folder public , jadi harus ambil ke dalam satu langkah ( cd ..) .

Setelah itu, kita edit file MY_Router.php (yang telah kita copy dari file compress tadi ke folder system/application/libraries).
ubah :

APPPATH.'modules/' => '../modules/',

menjadi :

APPPATH.'../../modules/' => '../../../modules/',

karena ceritanya kita akan meletakkan modules nya diluar folder system 🙂

Nah, setelah semua siap, kita boleh tambahin file .htaccess di folder public untuk meremove index.php dari URL yang kita akses.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Dengan syarat, kita aktifkan dulu module mod_rewrite dulu yang bisa kita aktifkan dengan meng-uncomment (hilangkan tanda ; ) di file httpd.conf di dalam folder web container kita ( xampp, appserv, etc)
;LoadModule rewrite_module modules/mod_rewrite.so
———
Ok, let’s setting the configuration :
Buka file routes.php dalam folder system/application/config :
ubah

$route['default_controller'] = "welcome";

menjadi

$route['default_controller'] = "mod_default/welcome";

Habis itu, buka file config.php dalam folder system/application/config :
ubah :

$config['base_url']    =  "http://www.example.com";

menjadi :

$config['base_url']    = "http://".$_SERVER['SERVER_NAME'].str_replace("index.php","",$_SERVER['SCRIPT_NAME']);

———
That’s all, sekarang kita coba buat contoh kasus panggil models dari module yang berbeda : kita buat file testmodel.php di dalam folder mod_sample/models (di dalam  module mod_sample , buat folder models).
berisi contoh berikut :

<?php

class Testmodel extends Model
{
 public function __construct()
 {
 parent::Model();
 }

 public function testfunc()
 {
 echo "this is test func from sample module";
 }
}

Setelah itu, coba deh kita panggil di controllers welcome di module mod_default,( kita tadi telah CUT controllers nya ke folder mod_default) seperti berikut :

<?php

class Welcome extends Controller
{
 function Welcome()
 {
 parent::Controller();
 }

 function index()
 {
 $this->load->model('mod_sample/Testmodel','tm');
 $this->tm->testfunc();
 }
}

/* End of file welcome.php */
/* Location: ./modules/mod_default/controllers/welcome.php */

———–

ok coy, sekarang kita coba panggil di browser :

Padahal kita panggil itu dari mod_default, kalau udah jalan , ya berarti udah berhasil :).

Referensi :
http://codeigniter.com/forums/
http://codeigniter.com/wiki/Modular_Extensions_-_HMVC/

Menyembunyikan Image path (PHP)

Posted in tips and tricks, Tutorial PHP by samsonasik on November 15, 2009

Untuk kebutuhan keamanan, baiknya kita menyembunyikan path file asset ( misal gambar ) dari web kita. Di php, kita bisa menggunakan header dengan content-type image untuk menyembunyikan target gambar yang diambil dengan kode program seperti berikut  :


<?php
 header('Content-type: image/jpeg');
 $image = "path/to/image/file.jpg";
 $fp = fopen($image,"r");
 echo fpassthru($fp);

?>

Demikian, semoga bermanfaat :).

Tagged with:

SubQuery pada Zend_Db_Select

Posted in tips and tricks, Tutorial PHP by samsonasik on October 30, 2009

Anggaplah kita akan menjalankan query seperti berikut :

select is_add from dwt_menushow where menu_id = any(select menu_id
from dwt_menu where menu_link = 'mfirst') and groupuser_id = 1

Maka yang harus kita lakukan adalah mengkonversi penggunaan Zend_Db_Select pada subquery menjadi String.

$exp = $this->db->select()->from($this->prefixDbDefault."menu",
   array('menu_id'))
 ->where("menu_link = 'mfirst' ")
 ->__toString();

Setelah itu, baru kita panggil :

$select = $this->db->select()->
  from($this->prefixDbDefault."menushow",array("is_add"))
 ->where("menu_id = any( $exp ) and groupuser_id = 1 ");

//cek ...
echo "<pre>";
print_r($this->db->fetchAll($select));
echo "</pre>"

Referensi : http://old.nabble.com/

Tagged with:

PHP 5.3 safe mode

Posted in tips and tricks, Tutorial PHP by samsonasik on October 29, 2009

HP 5.3 disamping banyak mempermudah, di sisi lain jg sangat strict, sehingga yg terbiasa coding-nya agak acak-acakan (seperti saya, he.he.he.), akan sangat kesulitan ketika upgrade ke versi ini. Nah, cara mengatasinya adalah penggunaan error_reporting, cara ini saya anggap ampuh untuk menangani kode program yang strict tersebut, seperti : undefined variable, Undefined offset array, header already sent,  dan lain2. Sebagai contoh, kita definisikan error_reporting(0) di line pertama :

<?php
error_reporting(0);
//coding php yg lainnya ...

Untuk melihat perbandingan pelevelan-nya, bisa dilihat di sini

PHP 5.3 session.save_path

Posted in tips and tricks, Tutorial PHP by samsonasik on October 29, 2009

PHP 5.3 memang aneh bin ajaib, walaupun banyak sekali menuai kritik karena banyak mengangkat deprecated function, tapi tetap aja banyak pula yang tertarik karena fitur2 nya yg luar biasa, lihat PHP 5.3.0 Release Announcement . Karena ketertarikan itu pula-lah, banyak yg mencoba meng-kick hal-hal yang mengganggu itu, salah satu di antara-nya adalah saya (wkwkwk…).

Kemarin ceritanya, saya mencoba php 5.3 untuk Zend Framework. Nah, pas pakai session, ternyata ada masalah, masalahnya adalah halaman menjadi blank, tanpa respon apapun. Dug…, saya langsung panik, gmn neh…, nah, setelah itu saya cari2 tahu dengan mendebug line demi line (karena sebelumnya saya tidak tahu bahwa letak kesalahannya berada pada Zend_Session_Namespace). Nah, ternyata ketemu, permasalahannya ada di baris setelah instansiasi kelas Zend_Session_Namespace. Saya langsung cari tahu di Google , nah, ketemu, cara mengakalinya dengan mendefinisikan secara eksplisit session.save_path di php.ini, misal

;;;;
session.save_path = "/tmp"
;;;;

Pastikan directory tujuan bersifat writable agar bisa ditulisi.
Selamat mencoba :).

Menangani error mysql command line : ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)

Posted in mysql docs, tips and tricks by samsonasik on July 6, 2009

Pernahkah anda pas ngerun mysql di command line mengalami error seperti ini ?

errormysql

Nah, cara mengatasinya adalah membuat ‘link’ ke file /var/run/mysqld/mysqld.sock, caranya :

mysqlhandling

Version Control menggunakan Bazaar

Posted in Teknologi, tips and tricks by samsonasik on June 20, 2009

Version control atau biasa kita sebut SCM (Source code Management) adalah management source ,dokumen, program, dan file komputer yang lain. Dengan adanya Version Control ini, segala perubahan akan dicatat dan diidentifikasikan dengan revision number, –akan sangat berguna untuk kerja tim, agar pekerjaan tidak tumpang tindih, dan untuk control revisi source–. Ada banyak Version control yang bisa kita download, antara lain: SVN, Git, Mercurial, Bazaar, dan lain-lain. Pada dokumentasi kali ini, kita akan coba mengupas tentang Bazaar,  Jika kita menggunakan ubuntu, kita bisa install dengan cara apt-get install bzr bzrtools , kalau yg lain, bisa download sendiri , nah, bagaimana cara mempergunakan tools ini ? Berikut langkah2 yang harus dilakukan :


1. Membuat repository

Direktori ini berisi file2 yang nantinya bisa dicloning oleh banyak user. Untuk lebih jelasnya, akan saya beri contoh sederhana :

a. Saya buat direktori /media/disk-1/repositories/documentation

b. Buat direktori di dalamnya bernama RepoDocumentation

c. Buat contoh file yang akan kita clone, misal RepoTest.java

class RepoTest {

public RepoTest() {

System.out.println(“object RepoTest terbentuk”);

}

public static void main(String args[]) {

new RepoTest();

}

}

d. Init repo:

e. Add file-file dalam direktori

f. Kalau ada file yg ditambahkan, berarti ada perubahan, maka kita harus commit perubahan tersebut agar bisa diclone jg oleh user lain :


2. Checkout

Untuk mengkloning file repository kita, maka kita harus mengkloning dengan cara checkout, atau bisa juga branch, untuk dokumentasi kali ini, saya akan mencoba memakarkan tentang checkout saja.

Misal, user A ingin kloning seluruh file  di folder repository Repocumentation di direktory /media/disk-1/workspace/A

Lalu, user B ingin kloning seluruh file  di folder repository Repocumentation di direktory /media/disk-1/workspace/B

3. Update

Ceritanya, user A, melakukan perubahan di file RepoTest.java

class RepoTest {

public RepoTest() {

System.out.println(“object RepoTest terbentuk”);

}

public void go()

{

System.out.println(“Start the Game”);

}

public static void main(String args[]) {

new RepoTest().go();

}

}

user menambahkan method go() dan menambahkan .go() setelah new RepoTest() , maka user A harus meng-commit file tersebut agar user B bisa mendapatkan file paling up to date.

Kemudian, user B bisa mengupdate perubahan tersebut (sebelumnya, bisa mengecek status up to date file):

maka, otomatis, user B telah mengupdate perubahan yg terjadi .

4. Konflik

Pada kasus di atas, tidak akan terjadi masalah karena user B mengupdate file dari perubahan user A tanpa melakukan perubahan terlebih dahulu. Akan tetapi, jika user B melakukan perubahan pula, dan user A melakukan commit file terlebih dahulu (jika beda line , maka akan saling melengkapi, jika pada line yang sama, maka bazaar akan membuat 3 versi file, yaitu file sebelum diubah (BASE), file setelah diubah user B (THIS), dan file yg telah dicommit oleh user A (OTHER)).

Contoh user A mengganti method go() menjadi method mulai() lalu melakukan commit, kemudian user B mengganti method go() menjadi method start() :

maka ketika user B, melakukan bzr up , akan tampil seperti berikut :

Lalu, setelah dicek, benar akan terjadi 3 file :

Nah, di sinilah waktu nya user A dan user B berkomunikasi, he..he.., setelah itu menentukan file mana yg benar, punya A, punya B, atau mau dibalikkan ke kondisi seperti semula :

anggap saja yg benar adalah file punya B, berarti kita harus copykan isi file yang THIS ke file yang diubah,setelah itu, kita tentukan kebenaran file dengan cara di resolve :

jangan lupa, harus dicommit lagi :

setelah itu, user A bisa mengupdate :