All Posts By

doonot

Cake-PHP

Generate random strings using PHP

Sometimes you want to create random strings. The can be handy in different cases such as a random session_id, a temporary password when the user resets it and many more. This is a PHP function that accepts the length of the string as a parameter. The default value in case nothing is provided is 10:

public function generateRandomString($length = 10) {
  
  $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  $charactersLength = strlen($characters);
  $randomString = '';
  
  for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
  }
  return $randomString;
}

Call it like this:

$randomString = generateRandomString(15);
Cake-PHP

UPDATE SINGLE FIELD IN DB USING CAKEPHP

This code shows how to update one single field in the database using CakePHP 2.x. It is as simple as this:

$this->User->id = $id;
$this->User->saveField('is_active', 1);

In case we are in an other controller or model as User, we can simply load the User model:

$this->loadModel('User');
$this->User->id = $id;
$this->User->saveField('is_active', 1);
2000px-PHPCode_HelloWorld

SO THIS IS WHERE IT ALL BEGINS

So this is it, my first post on my own blog!

I singed up to Simons newsletter on Devtactiv some weeks ago and got an interesting newsletter today. He encourages developers to write about their experience on their own blog. So let’s do it. Even tough I really do not feel like an expert or a pro at all, I think that some of my experiences might be helpful for other developers out there. I think I am going to talk about my recent projects with Ionic and AngularJS, a really nice cross-plattform framework to create native applications using web technologies!

Talk to you guys soon!