Showing posts with label cakephp. Show all posts
Showing posts with label cakephp. Show all posts

Monday, July 25, 2016

How to check Cron jobs



In the previous article I have shown you to configure cron jobs. Somebody asked me how to check weather cron jons is processing.

So, if you haven't known what is cron jobs please read follow this cron jobs

There are many way to check your cron jobs. To do it you have to :

1- Turn on your terminal and type

   -> service crond status (it will show your cron is running or not)

2- you can test it directly with your Shell

    -> cd /var/www/vhost/yourroot/html/app
   -> Console/cake News (if your code error it will be written into log file)

I hope this two steps will be able to involve your part. so if you think this article is important please help to share to everyone.


Set up cron jobs or crontab in Cakephp




Before stating to set up Cron jobs in your server you have understand and know what the Cron jobs is?

Cron is a Linux utility which schedules a command or script on your server to run automatically at a specified time and date. A cron job is the scheduled task itself. Cron jobs can be very useful to automate repetitive tasks.

Cron syntax
  */5  *    *    *    *  cd /full/path/to/app && Console/cake myshell myparam
# *    *    *    *    *  command to execute
# │    │    │    │    │
# │    │    │    │    │
# │    │    │    │    \───── day of week (0 - 6) (0 to 6 are Sunday to Saturday,
# |    |    |    |           or use names)
# │    │    │    \────────── month (1 - 12)
# │    │    \─────────────── day of month (1 - 31)
# │    \──────────────────── hour (0 - 23)
# \───────────────────────── min (0 - 59)
To understand more please follow this link console-and-shells

1 - Create model News.php
App::uses('AppModel', 'Model');
class News extends AppModel
{
    public function sendNews()
    {
 $this->updateAll(array('is_disabled' => 1), array('delivery_time' => date('H:i').':00'));
    }
}

2- Create NewsSell in Cosole.

class NewsSell extends AppShell
{
   public function main()
   {
    App::import('Model', 'News');
    $News  = new News();
    $News->sendNews();
   }
}

3- Write command in crontab

-> type "crontab -e" in your terminal
->  set cron path "*/1 * * * * /var/www/vhosts/yourwebroot/html/app/Console/cake News"
-> save

Finally, I hope that this article will help you to get reach at the point.

Problem with cron jobs cakephp.





Tuesday, March 22, 2016

Create component to validate IPN (Instant Payment Notification) with Cakephp


It's seem to be for senior programmer, but I just want to let somebody know the benefit or how to implement the IPN of PayPal using PHP or Cakephp, before you can understand what to do with IPN you have take a look this website.

If you don't know at all about Paypal please read the previous article : Paypal
class IpnComponent extends Component
{
   public function validate_ipn_data($data_ipn)
   {
     //Change these with your information
     //Sandbox for testing or empty ''
     $site = @$_SERVER['SERVER_NAME'];
     $paypalmode = $site === 'your_site' ? '' : 'sandbox';

    if ($data_ipn) {
       if ($paypalmode=='sandbox') {
          $paypalmode     =   '.sandbox';
       }
       $req = 'cmd=' . urlencode('_notify-validate');
       foreach ($data_ipn as $key => $value) {
           $value = urlencode(stripslashes($value));
           $req .= "&$key=$value";
        }
    $ch = curl_init();
    $url_ = 'https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr';
    $host_ = 'Host: www'.$paypalmode.'.sandbox.paypal.com';
    curl_setopt($ch, CURLOPT_URL, $url_);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array($host_));
    $res = curl_exec($ch);
    curl_close($ch);

    if (strcmp ($res, "VERIFIED") == 0) {
         $item_number = $data_ipn['item_number'];
         $model      = ClassRegistry::init('Reservation');
                $model->id = $item_number;
                $model->save(array('is_paid' => 1));
    }
  }
 }  
}
1- Please create file in Component and pass the code above, then save.
2- You have to load the component in your controller
3- Create a function and call the  validate_ipn_data from IPN component
Note : Make sure that your URL pointed to Paypal.

Monday, March 21, 2016

Check OS and Browser Agent with PHP




The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.

Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.

In this case I will show you how to detect the Os or Browser Agent using PHP ,

* Check OS
$agent = $_SERVER['HTTP_USER_AGENT'];
// get os
if (preg_match('/linux/i', $agent)) {
    $os = 'linux';
} elseif (preg_match('/macintosh|mac os x/i', $agent)) {
    $os = 'mac';
} elseif (preg_match('/windows|win32/i', $agent)) {
    $os = 'windows';
}

* Check Browser Agent
if (preg_match('/Chrome/i', $agent)) {
    if ($os == 'windows') {
        //impleted;
     } else {
        //impleted;
     }
} elseif (preg_match('/Firefox/i', $agent)) {
   if ($os == 'windows') {
      //impleted;
   } else {
     //impleted;
   }
} elseif (preg_match('/Safari/i', $agent)) {
   if ($os == 'windows') {
      //impleted;
   } else {
      //impleted;
   }
}
- Let's enjoy!

Friday, February 5, 2016

Different language message error from Model Cakephp


That is just a small trick how how we can make our website to be multiple language. For the concept is not different from other
framework, by the way you have understand about folder structure of Cakephp.

In this case you will see the Local folder which its contain the two folder inside.

I have created two folder of language "en and jp".

1- Create language folder. ex. ('en and jp')



2- Create file with extension ".po"
3- There are two key word in the file which you have to understand :
    msgid : it is the key or id which represent the message as a global
    msgstr: it is the message of the key a head
4- Use in model. ex.
public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => array('notBlank'),
                'message' => 'This field is required!'
            )
        ),
        'password' => array(
            'required' => array(
                'rule' => array('notBlank'),
                'message' => 'This field is required!',
            ),
            'min_length' => array(
                'rule' => array('minLength', '5'),
                'message' => 'Password must over 5',
            )
        ),
);

5- check in the file .po syntax
    a- Example in en folder :

msgid "This field is required!"
msgstr "This field is required!"

msgid "Please enter the same value again!"
msgstr "Please enter the same value again!"

msgid "Password must over 5!"
msgstr "Password must over 5!"

msgid "Email already exist!"
msgstr "Email already exist!"

msgid "Please enter valid phone number!"
msgstr "Please enter valid phone number!"

msgid "This field must be number!"
msgstr "This field must be number!"

msgid "Invalid email format!"
msgstr "Invalid email format!"

   b- Example in jp folder :
msgid "This field is required!"
msgstr "必須項目です。"

msgid "Please enter the same value again!"
msgstr "必須項目です。"

msgid "Password must over 5!"
msgstr "パスワードは5文字以上を入力ください。"

msgid "Email already exist!"
msgstr "入力されたEメールは既に存在しています。"

msgid "Please enter valid phone number!"
msgstr "電話の形式ではありません。"

msgid "This field must be number!"
msgstr "数値ではありません。"

msgid "Invalid email format!"
msgstr "Eメールの形式ではありません。"

6- Please configure the language in AppController :

Configure::write('Config.language', 'jp or en');

Ok, that is. Let's enjoy.

Tuesday, November 17, 2015

Call and use helper in controller Cakephp

Somebody said that there would have many ways to call Helper to use in view , but inspire I would show you how to implement it in Controller.php

class YourContrller extends Objects{
  pubic function yourfunction()
  {
  App::import('Helper', 'String'); 
  $string = new StringHelper(new View());
 
  $string->yourFunctionHelper();
 }
}


StringHelper.php

class StringHelper extends AppHelper{
  
   public function yourfunction()
   {
     .....
   }
} 

Saturday, November 14, 2015

Check and Remove Flash Session with Cakephp


Controller.php
 public function contact()
    {
        if($this->Session->check('Message.message_send_success')) {
            $this->Session->delete('Message.message_send_success');
        }
        if ($this->request->is('post')) {
            $author = $this->viewVars['get_author'];

            if (!$author) {
                return $this->Session->setFlash(
                        'Both fields are required!',
                        'default',
                        array('class' => 'redTxt'),
                        'message_send_error');
            } else {
                $sender_name = ucfirst($author[0]['User']['username']);
                $email       = $author[0]['User']['email'];
                $user_id     = $author[0]['User']['id'];
                $this->loadModel('User');
                    $title = $this->request->data['User']['title'];
                    $body  = $this->request->data['User']['body'];
                    if (!$title && !$body) {
                        return $this->Session->setFlash(
                            'Both fields are required!',
                            'default',
                            array('class' => 'redTxt'),
                            'message_send_error');
                    }
                    $Email = new CakeEmail();
                    $Email->from(
                        array($email => $title))
                        ->to($email)
                        ->subject($title)
                        ->emailFormat('html')
                        ->send('From '.h($sender_name).' '.h($body));
                    $this->Session->setFlash(
                        'The message has been send!',
                        'default',
                        array('class' => 'alert alert-success'),
                        'message_send_success');
                }
        }
        $this->set('title', 'Contact Us');
    }
}
view.php
Session->check('Message.message_send_success')): ?> 

THANK FOR YOUR CONTACT US!

your message has been send to us successfully.
Go back to home

Monday, November 9, 2015

Get properties from beforefilter in Cakephp to other function



That is just a trick which most of the developers are still wondering that is there a ways to get some properties from beforefilter in Cakephp to use in other function ? so here is the ways to do.

AppController.php
public function beforeFilter()
{
$user_id = ($this->Auth->user('id') != '' ? $this->Auth->user('id'): $author[0]['User']['id']);
$this->User->recursive = -1;
$get_author = $this->User->find('all',
     array(
        'conditions' => array('User.id' => $user_id)
     ));
$this->set('get_author', $get_author);
}
FavoritesController.php
public function get_vaforite(){
   pr( $this->viewVars['get_author']); 
}
Result :
Array
(
    [0] => Array
        (
            [User] => Array
                (
                    [id] => 563c9401-445c-4d94-9151-5edb0a79370f
                    [username] => samphors bb
                    [password] => 3076ca74262cf933d1bbb4ee97474255f9aa8d9a
                    [facebook] => 
                    [email] => samphors.info@gmail.com
                    [address] => March dela deja
                    [mobile] => 1234567890
                    [birthdate] => 2015-11-10
                    [country] => Cambodia
                    [partner_country] => Italy
                    [height] => 6
                    [foot_size] => 3
                    [partner] => Dora vanndya
                    [partner_birthdate] => 2015-11-18
                    [partner_height] => 2
                    [partner_foot_size] => 5
                    [role] => 
                    [token] => 
                    [created] => 2015-11-06 20:50:25
                    [modified] => 2015-11-07 00:20:07
                )

        )

)