顯示具有 PHP 標籤的文章。 顯示所有文章
顯示具有 PHP 標籤的文章。 顯示所有文章

2012年4月22日 星期日

如何正確的unserialize()

今天在修Bug時,發現到一個問題,在PHP常常會用到 serialize() & unserialize() 這個函式,但是假如今天存進去的資料格式不正確,要如何驗證資料的正確性真且安全的反解出來,我今天就遇到了這個"Notice: unserialize(): Error at offset 0 of 63 bytes "的訊息,代表資料格式不正確,無法正確的反解資料,於是我去PHP官網找到了別人寫的一個function。

function safe_unserialize($serialized) {
    // unserialize will return false for object declared with small cap o
    // as well as if there is any ws between O and :
    if (is_string($serialized) && strpos($serialized, "\0") === false) {
        if (strpos($serialized, 'O:') === false) {
            // the easy case, nothing to worry about
            // let unserialize do the job
            return @unserialize($serialized);
        } else if (!preg_match('/(^|;|{|})O:[0-9]+:"/', $serialized)) {
            // in case we did have a string with O: in it,
            // but it was not a true serialized object
            return @unserialize($serialized);
        }
    }
    return false;
}

這樣應該就可以驗證假如存入資料不正確時,可以正確的回傳一個值,而不跑出error。

2012年4月17日 星期二

[PHP] 將Object轉成Array

由於最近都改用物件的方法在寫程式,所以大都也用物件的方法取得變數,但是有時候需要回傳為json的資料型態時,PHP必須使用json_encode的函式將array轉成json,這時候就必須將物件的所有資料轉成一個array,就找到了網路上有人這樣做。

function objectToArray($object)
{
    if(is_object($object))
        $array = get_object_vars($object);
    return $array;
}

不過需要注意的地方是:

  • 假如是在object內轉出array則不必注意變數型態(連private都會讀取)
  • 如果是在外部將object轉出array則必須將變數設為public才行,否則無法取得變數

例如:

  • 內部

    class Student{
        public      $name;
        protected   $height;
        private     $weight;
    
        function toArray()
        {
            if(is_object($this)
                 $array = get_object_vars($this);
            return $array;
        }
    }
    
    var_dump($student->toArray());
    // Array('name' => XX, 'height'=> 170, 'weight' => 48)
    
  • 外部

    class Student{
        public      $name;
        protected   $height;
        private     $weight;
    
    
    }
    function objectToArray()
    {
       if(is_object($this)
            $array = get_object_vars($this);
       return $array;
    }
    var_dump(objectToArray($student));
    // Array('name' => XX)
    

需注意其中的差異

2012年4月15日 星期日

[PHP] 取得使用者正確IP

        function getIp()
        {
                if(empty($_SERVER['HTTP_X_FORWARDED_FOR']))
                {
                        $proxyIp        = split(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                        $UP             = $proxyIp[0];
                }
                else
                {                        $ip     = $_SERVER['REMOTE_ADDR'];
                }
                return $ip;
        }

2012年4月3日 星期二

[PHP] 如何用timestamp計算年紀?

$birthday = time();
$now      = time();
$age      = floor(($now - $birthday)/(60*60*24*365));

2012年2月28日 星期二

[PHP] DataMapper 範例寫法

建立User model

class User{

    protected name;

    public function __construct(array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }
 
    public function __set($name, $value)
    {
        $method = 'set' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Invalid guestbook property');
        }
        $this->$method($value);
    }
 
    public function __get($name)
    {
        $method = 'get' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Invalid guestbook property');
        }
        return $this->$method();
    }
 
    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }

    public function setName($text)
    {
        $this->name = (string) $text;
        return $this;
    }

    public function getName()
    {
        return $this->name;
    }
}

建立User mapper

class UserMapper{
    public function fetch($ID, $User)
    {
        $result = $SQL ...
        //自行設定
        $User->setOptions($result);
        //OR
        $result = $this->setup($result);
        $User->setOptions($result);
        //欄位名稱必須與Model定義的變數名稱相同。
    }
    
    public function setup($result)
    {
        $data = array(
           ...
        );
        return $data;
    }
}

Controller 的使用

function user()
{
    $User = new User();
    $userMapper = new UserMapper();
    $userMapper->fetch($ID, $User);
    
    echo $User->getName();
}

//Output
//Ciao Chiang(Name)
//看資料庫的資料是甚麼

2011年10月24日 星期一

[PHP] Coordinate Translate(經緯度轉換)

Code

function CovertCoordinate($Position){
  $deg = floor($Position);
  $min = floor(($Position - $deg)*60);
  $sec = round((((($Position - $deg)*60) - $min)*60),3);
  return ($deg * 3600000) + ($min * 60000) + ($sec * 1000);
}

function RevertCoordinate($Position){
  $deg = floor($Position/3600000);
  $min = floor(($Position - ($deg * 3600000))/60000);
  $sec = (($deg * 3600000) - ($min * 60000))/1000;       
  return $deg + ($min / 60) + ($sec / 3600);
}