Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to generate a pseudo-random string of bytes

    • 0
    • 2
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 291
    Comment on it

    sometime we need to generate a random string of byte, For this purpose openssl_random_pseudo_bytes method is used,which gives us a random string of  byte.

    Syntax

    string openssl_random_pseudo_bytes (  $length ,$crypto_strong )

    Parameters

    openssl_random_pseudo_bytes method have two parameter one is length and other one is crypto_strong. These are explain below.

    Length

    The length parameter contain integer number which define the length of the byte code which are going to be generated.

    Crypto_strong

    This parameter contain a boolean value(true/false) that determine algorithm which is used should be strong or not.

    In below code we are using openssl_random_pseudo_bytes method for generating a key which we will send with a link to user email id for reseting his password.

    public function forgotPassword(){
        
              $this->layout="main";
    	    if (!empty($this->request->data)) {
               
    	       $result = $this->User->find('first', array('conditions' => array('User.email' => $this->request->data['User']['email'])));
    	    
    	       /*Create msg*/
    	       $i=16;
    	       $cstrong = true;
    	       $bytes = openssl_random_pseudo_bytes($i, $cstrong);
    	       $hex   = bin2hex($bytes);
               
    	              
    	       $msg='';
    	       $msg.='Click on the link below for reseting your password.';
               $msg.='<a href="http://localhost/health/Users/resetPassword/'.$hex.'">Reset Password</a>';
    	       $msg.='';
    	       
    	       $msg=wordwrap($msg,70);
    	       try{
    	        $Email = new CakeEmail();
    	        $Email->from(array('me@example.com' => 'My Site'));
    	        $Email->to($this->request->data['User']['email']);
    	        $Email->subject("Forgot Password");
    	        $Email->send($msg);
    	        $this->request->data['User']['id'] = $result['User']['id'];
    	        $this->request->data['User']['h_key'] = $hex;
    	        if ($this->User->save($this->request->data)) {
    	            $this->Session->setFlash('We have sent a link to your mailbox for reseting your password.');
    	        }
    
    	    }
    	    catch(Exception $e){
    	        echo 'Error:'.$e->getMessage();
    	    }
    	 }
       }

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: