[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.


function afterSave($created) {
if ($created) {
if ($this->hasField(‘ip_address’)) {
$this->saveField(‘ip_address’, env(‘REMOTE_ADDR’));
if ($this->hasField(‘host_name’)) {
$this->saveField(‘host_name’, @gethostbyaddr(env(‘REMOTE_ADDR’)));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.