Category Archives: Chỉ dẫn lập trình

Using multiple select boxes in PHP

HTML

<form action=”<?php echo $_SERVER[‘PHP_SELF’]; ?>” method=”post”>
<select name=”test[]” multiple=”multiple”>
    <option value=”one”>one</option>
    <option value=”two”>two</option>
    <option value=”three”>three</option>
    <option value=”four”>four</option>
    <option value=”five”>five</option>
</select>
<input type=”submit” value=”Send” />
</form>

PHP

<?php
    $test=$_POST[‘test’];
    if ($test){
        foreach ($test as $t){echo ‘You selected ‘,$t,'<br />’;}
    }
?>

How do I get the cursor position in the textarea element?

<script type=”text/javascript”>
//IE4+, Mozilla/Gecko
function getCaretPos(obj)
{
  obj.focus();
  
  if(obj.selectionStart) return obj.selectionStart; //Gecko
  else if (document.selection) //IE
  {
    var sel = document.selection.createRange();
    var clone = sel.duplicate();
    sel.collapse(true);
    clone.moveToElementText(obj);
    clone.setEndPoint(‘EndToEnd’, sel);
    return clone.text.length;
  }
  
  return 0;
}
</script>

PHP Manual : Patterns

Patterns
Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Factory
The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for “manufacturing” an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Singleton
The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.

Dùng khi:
– Bạn không muốn kế thừa class cha.
– Bạn không muốn hao tốn resource khi phải tạo ra nhiều đối tượng (object)
– Bạn không thích reference tới object đó (vì dù muốn dù không bạn cũng phải tạo đối tượng qua từ khóa new rồi mới xài nó được.)
– Điều hành lớp qua phương thức static. Chỉ cho phép ta tạo một đối tượng duy nhất.

Crop and resize Image

<?php
/**
 * @author: huyphungvan
 * @date: 9:11 PM 8/28/2009
 */
function cropImage($src, $size, $target = null) {
    if ($target == null) {
        $name = basename($src);
        $pos = strrpos($name, ‘.’);
        $name = ($pos === false) ? $name : substr($name, 0, $pos);
        $target = $name . ‘_’ . implode(‘x’, $size) . ‘.jpg’;
    }
    $info = GetImageSize($src);
    $width = $info[0];
    $height = $info[1];
    $mime = $info[‘mime’];
    $type = substr(strrchr($mime, ‘/’), 1);
    $image_types = array(‘jpeg’, ‘png’, ‘gif’, ‘bmp’);
    if (!in_array($type, $image_types)) $type= ‘Jpeg’;
    $img_create_func = ‘ImageCreateFrom’ . $type;
    list($w, $h) = $size;

    $scale_x = $width / $w;
    $scale_y = $height / $h;
Continue reading →