[CakePHP]How to save IP address or Host name automatically


I’ve been using CakePHP a lot so I would like to release the tips little by little during break.

If it’s CGM type web service, users do some actions and keep them in DB. It’s usual to keep user’s IP addresses at that time to follow users . It takes time to write the codes in all of models to keep IP so it’ll be way easy if you do like example below.

In that case, type “ip_address” in field of the table you would like to save IP address, type also “host_name” in field if you would like to save host name.
Then keep it in “beforeSave” of app_model.php , the table you added the field will save all of IP addresses automatically.



app_model.php

/**
 * save IP address automatically if DB has `ip_address` field
 */
    function beforeSave() {        
        if ($this->hasField('ip_address') && empty($this->id) && empty($this->data[$this->alias][$this->primaryKey])) {
            $this->data[$this->name]['ip_address'] = env('REMOTE_ADDR');
        }
        if ($this->hasField('host_name') && empty($this->id) && empty($this->data[$this->alias][$this->primaryKey])) {
            $this->data[$this->name]['host_name'] = gethostbyaddr(env('REMOTE_ADDR'));
        }        
        return true;
    }
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
This entry was posted in CakePHP. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted %A %B %e%q, %Y at %I:%M %p | Permalink

    Nice tip, but you can check the existence of the field with Model::hasField($field_name).

  2. admin
    Posted %A %B %e%q, %Y at %I:%M %p | Permalink

    Kalt, thanks for comment.
    I agree with you and it’s better to use Model::hasField($field_name) and I fixed the code.

One Trackback

  1. [...] This post was mentioned on Twitter by 長谷川 剛志, Masaya Iwata. Masaya Iwata said: Blog Updated, [CakePHP]自動でip addressやホスト名を保存する方法 http://bit.ly/aU22ZZ [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>