Saturday, November 29, 2014

Amazon ec2 phpmyadmin not working after upgrading apache and php

There is new permission model in use by apache 2, hence do the following,

<Directory "/usr/share/phpmyadmin">
   #Order Deny,Allow
   #Deny from all
   Options All
   AllowOverride All
   Require all granted
</Directory>

Wednesday, September 10, 2014

Post or share to facebook page with out login

Facebook has now updated its PHP SDK to version 4, and also try to update your graph api to version 2.0 before December 25 2014 because they are shutting down support for 90% of previous graph API's functionality.

Now for posting to a Facebook page without log in you need a long lived page access token and page-id to which you are trying to post. You can find more information on page access tokens here.

I assume that you have a Facebook app and a Facebook page. You will be posting to your Facebook pages via your Facebook app. To create an app go to https://developers.facebook.com/  and click on App->Create a New App. After you provide a name and namespace for you app you will be shown an app dashboard where you can see your app-id/client-id and app-secret/client-secret. Then go to Settings and click on Add platforms and select the platform of your choice. If you choose website then you may want to enter the App domain,site URL and mobile site URL (which in most cases will be the same e.g: http://www.example.com). After that go to App Details and provide a long description for your app, logo (1024x1024) and privacy policy URL. Also Facebook is not accepting white backgrounds for logo and the dimensions has to be exact  :). You can see status of your Facebook app from Status & Review. Now you need make your app live, you can do that by clicking on a [?] right next to This app is in development mode. Now you need to provide extended permissions to your app so that your app can post on behalf of page. You can find it from Tools->Graph API Explorer. Now click on get access token a pop up will appear where you can find extended permission from which you have to select manage_pages, publish_stream and read_stream.





The following are the steps for posting to a Facebook page with out log in using long lived page access tokens. I assume that you have successfully created a Facebook app and a Facebook page before proceeding to the below steps:

Step 1:  Authorize first. Enter the following URL in your browser and specify your redirect URL.


   https://graph.facebook.com/oauth/authorize? 
    type=user_agent&
    redirect_uri=http%3A%2F%2Fwww.your-domain.com/my-redirect-url&
    client_id=MY_APP_ID&
    scope=manage_pages,publish_actions,status_update

   MY_APP_ID is the app id. you can get if from your app dashboard. If you already haven't provided extended permissions Facebook will ask for authorization.

Now you will be redirected to your redirect URL and at the end of the URL there will be a authorization token. Now copy that access token and go to step 2

Step 2:  Request for long term access token. Enter the following URL in your browser and specify your App id, App Secret and access token received from Step 1.

https://graph.facebook.com/oauth/access_token?
client_id=paste_your_app_id_here
&client_secret=paste_your_app_secret_here

&grant_type=fb_exchange_token&fb_exchange_token=paste_your_authorization_access_token_from_step1_here

Now you will get another access token which will be displayed in browser. Copy that access token.

Step 3: Retrieve  long term page access token. Enter the following URL in your browser and specify your access token received from Step 2.

https://graph.facebook.com/me/accounts?access_token=paste_your_access_token_from_step2_here

Now you will get a JSON result as below:

{
   "data": [
      {
         "category": "some_category",
         "name": "your name",
         "access_token": "a_very_long_lived_page_access_token_here",
         "perms": [
            "ADMINISTER",
            "EDIT_PROFILE",
            "CREATE_CONTENT",
            "MODERATE_CONTENT",
            "CREATE_ADS",
            "BASIC_ADMIN"
         ],
         "id": "your_app_id"
      }
   ],
   "paging": {
      "next": "https://graph.facebook.com/607528643/accounts?access_token=...."
   }

Now copy the access_token and use it to post to your Facebook page.

PHP example :

<?php 

     function facebook_post_to_page_via_long_access_tokens(){

          $accessToken = 'a_very_long_lived_page_access_token_here';

          $message = 'HelloWorld!!!';

          $link = 'http://some_link_to_share';

          $picture = 'url_to_picture_here';

          //Post via curl

          $ch = curl_init();

          curl_setopt($ch, CURLOPT_URL,"https://graph.facebook.com/v2.0/your_page_id_here/feed");

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"message=$message&picture=$picture&link=$link&access_token=$accessToken");

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $server_output = curl_exec ($ch);



curl_close ($ch);

        return $server_output;

      }
?>

Now you will get a post id, save it if you need it for any future use. Please don't hesitate to point out of any bugs or false information( if you feel so :( ) in this post. Hope this becomes helpful to anyone else. Enjoy!!!.








Wednesday, October 30, 2013

handling ajax redirects or 302 requests

With XMLHttpRequest in JavaScript , basically there is no way to detect a redirect in an AJAX request. The browsers AJAX object invisibly follow the redirects and only gives the last response header with response data. So to handle AJAX redirects one should devise their own method. An ideal method would be to check for AJAX request from server and give a response accordingly instead of redirect header.

One could check for ajax request simply by checking the request headers. the sample code is given below:

if( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  echo "AJAX REQUEST DETECTED";
}

Now you can simply echo the redirect url to your ajax response and redirect to that url from your browser. 

if( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$response = array('redirectUrl'=>'http://www.google.com');
  echo json_encode($response);
  exit();
}

From inside your JavaScript function you could parse the response and perform the action. 

In Codeigniter you can check for ajax request through 

$this->input->is_ajax_request();

In CakePHP :

$this->request->is('ajax')


Hope this helps!!! 

Dynamically created element event binding in jQuery

Many of the code had been re-written and many methods were deprecated since the release of jQuery 1.7. Now the current stable release is jQuery v1.10.2. You can see more details here. In earlier versions we could bind an event to an HTML element via methods such as .bind(), .live() etc.  As of jQuery version 1.7 these methods were deprecated and .on() methods was introduced.

The .on() method provides all the functionality required for attaching event handlers. Here i am going to give two examples one for implementing the .bind() method functionality and the another for implementing the .live() method.

Example for implementing the .bind() feature

In this section we are going to see an example for binding a click event for a DIV element via .on() method.

HTML
<div class='div1'></div>

We could bind an event to this div with the following code:

$('.div1').on('click',function(){
  alert('Hello World!');
}); 

Also note that this example will not fire the event for dynamically created elements.  

Example for implementing the .live() feature

.live() method was introduced in an attempt to simplify attaching event handlers for all elements via a selector, that are present now and in future( i.e dynamically created elements).   For this example suppose that the div with class name "div1" was created dynamically.

HTML
<div class='mainDiv'>
   <div class='div1'></div>
</div>

With live  jQuery.live() method one could attach an event to this div with the following code:

$('.div1').live('click',function(){
  alert('Hello World!');
}); 

The .live() code above is simple and easy to implement. But as the .live() method is deprecated and the .on() method is introduced things become a little bit different. Unlike .live() method , .on() is a more generic event handler method. We can use the .on() method to implement the .live() feature but with a small difference. You have explicitly provide a container for the element you wish to attach the event.
So to implment the .live() feature with the .on() method, the code would be:

 $('.mainDiv').on('click','.div1',function(){
  alert('Hello World!');
}); 

Here .mainDiv is the container which holds the dynamically created element.  In general one could use 

$(document.body).on('click','.div1',function(){
     alert('Hello World!');
});

But it would be better to provide an element that is closer to the HTML heirarchy( in our example mainDiv).

To remove events bound with .on() event we could use .off() method. Also .die() method can be used to remove event handlers previously attached using .live() method from the elements.

Thursday, October 24, 2013

Sending mail with Zend component in codeIgniter or PHP

Integrating zend with codeigniter is described here.
Now in Zend.php create a function, say sendMail and put the following code in it.

public function sendMail($toAddress,$fromAddress,$subject,$html=null,$attachments=array()){

//You can add more file types here.
$fileTypes = array(
  'default'=> Zend\Mime\Mime::MULTIPART_MIXED,
  'pdf'=> 'application/pdf',
  'png'=>'image/png',
  'jpg'=>'image/jpeg',
  'gif'=>'image/gif'
);

//Create a new mime message type
$mimeMessage=null;
$mimeMessage = new Zend\Mime\Message();
//Create a new mime part for html
$htmlContent = new Zend\Mime\Part($html);
$htmlContent->type= Zend\Mime\Mime::TYPE_HTML;
$mimeMessage->addPart($htmlContent); //add the part to mime message

//generateMessage() renders the Zend\Mime\Message content to a string $html = new Zend\Mime\Part($mimeMessage->generateMessage());
$html->type = Zend\Mime\Mime::MULTIPART_ALTERNATIVE . PHP_EOL . ' boundary="' . $mimeMessage->getMime()->boundary() . '"';

if($attachments){
//For multiple attachments
 foreach($attachments as $at){
    $mimePart = new Zend\Mime\Part(fopen($at['filePath'], 'r'));
    $mimePart->type = $fileTypes[$at['contentType']];//Zend\Mime\Mime::MULTIPART_MIXED;
    $mimePart->filename = $at['fileName'];
    $mimePart->encoding = Zend\Mime\Mime::ENCODING_BASE64;
    $mimePart->disposition = Zend\Mime\Mime::DISPOSITION_ATTACHMENT;
    $mimeMessage->addPart($mimePart);
 } 
}

//Creating the mail message
$mail = new Zend\Mail\Message();
$mail->setEncoding('ASCII')->addTo($toAddress)->addFrom($fromAddress)->setSubject($subject)->setBody($mimeMessage);

//Sending the Email
$transport = new Zend\Mail\Transport\Sendmail();
$transport->send($mail);

}

Now from your controller you can access this function using the following code:

$this->load->library('zend');
$attach = array( array(
'fileName'=>'warning1.png',
'filePath'=>'./fr/images/warning/warning1.png',
'contentType'=>'png'
),
array(
'fileName'=>'warning2.png',
'filePath'=>'./fr/images/warning/warning2.png',
'contentType'=>'png'
),
);
  $this->zend->sendMail('nouphal@masteroe.in','nouphaltklm@gmail.com','Zend Mail',"<html><body><div style='color:red'>HelloWorld</div></body></html>",$attach);

Wednesday, October 23, 2013

Password encryption in codeigniter with zend crypt module

Integrating zend with codeigniter is described here.
Now in Zend.php create a function, say encryptPassword and put the following code in it.

public function encryptPassword($pass){
$bcrypt = new Zend\Crypt\Password\Bcrypt();
$securePass = $bcrypt->create($pass);
return $securePass;
} 

Now from your controller you can access this function using the following code:

$this->load->library('zend');
$enc = $this->zend->encryptPassword('helloWorld!');

To verify or check the password create another function in Zend.php, say verifyPassword and put the following code in it.

public function verifyPassword($passwordTextToCheck,$encryptedPass){
$bcrypt = new Zend\Crypt\Password\Bcrypt();
return $bcrypt->verify($passwordTextToCheck, $encryptedPass);

}

Now from your controller you can access this function using the following code:

$this->load->library('zend');
$encryptedPassFromDB = '$2y$14$aR1YyFbg/UobJBzrLUJbPe57CfFWo300rT6zWBdh7Jj1bdcayN1im=';
$isValid = $this->zend->verifyPassword('helloWorld!',$encryptedPassFromDB);

Keep in mind that the verifyPassword function returns Boolean.

Monday, October 21, 2013

Display form validation error count in codeigniter V2

The following are the steps for showing the form validation error counts in codeigniter.
Step 1: Create a new file named MY_Form_validation.php under /application/libraries/. Remmeber to Ensure the following line is present in config.php
$config['subclass_prefix'] = 'MY_';

Step 2: Place the following code in the newly created MY_Form_validation.php:

class MY_Form_validation extends CI_Form_validation {

    public function __construct( $rules=array() )
    {
        parent::__construct($rules);
    }

    /*   This function will return the error count    */    
    function get_error_count()
    {
       return count($this->_error_array); 
    }
}

You can find more details about the core form validation class from here
Now you will be able to get the validation error count via the following code: 
$this->load->library('form_validation');
$this->form_validation->get_error_count(); 

Custom 404 page in codeigniter

By default CodeIgniter handles broken links(404), but when it comes to look and feel the default design becomes unpleasant.   In CodeIgniter we can override the default 404 functionality and implement our own custom 404 page very easily. The steps are described below:


Step 1: First create a new controller to handle the 404 page requests. For that just create a new controller under your controllers directory. For example, Say 'custom404Page'.
The controller would look like this 

class 
custom404Page extends CI_Controller {
 public function __construct(){
           parent::__construct();        
  }   
 public function index(){
  $this->output->set_status_header('404');
  $data['errorMessage'] = ' Ooops! Page not found'; 
  $this->load->view('custom404View',$data);//loading view
 }
}

Step 2: Open routes.php  under /application/config/ directory.
Step 2: Find the line which looks like $route['404_override'] = ''. If you cannot find such a line don't worry just add the above code in that file and point your controller file. For example in our case the code will be as below:

 $route['404_override'] = 'custom404Page'


Step4: Now create the view with your design and its all set and ready to roll. 

Another way for handling broken links is to override the Exception core class in CodeIgniter. There is a function called show_404() in CodeIgniter. You can either follow the method described in the above link or follow the following method.  

Step 1: Open config.php  under /application/config/ directory.
Step 2: Ensure the following line is present in config.php
$config['subclass_prefix'] = 'MY_';
Step 3: Now create a new file under /application/libraries/. Say MY_Exception and put the following code in it:

class MY_Exceptions extends CI_Exceptions{

    function MY_Exceptions(){

        parent::CI_Exceptions();
    }

    function show_404($page=''){    

        $this->config =& get_config();
        $baseUrl = $this->config['base_url'];
        header("location: ".$baseUrl.'error.html');//view file location
        /* Use this section if your view file is under views directory
          $CI = &get_instance();
$CI->load->view('custom404View', $data);
       */
        exit;
    }

}


Step 4: Now you can use show_404 function in any of your controllers. for example 

class test extends CI_Controller{
   public function index(){
         if(some condition){
            //do something
         }else{
             show_404();
        }
   }
}

Thursday, October 10, 2013

Integrate and use zend framework 2 with codeigniter

Zend framework 2(ZF2) is an open source framework using PHP 5.3+ with more than 15 million downloads. It should be kept in mind that ZF2 is not backward compatible with ZF1. ZF2 has an unique component structure and each component only have few dependencies on other components. Simply Zend call this architecture as "use-at-will" design.


If you want to integrate Codeigniter and ZF2 then that's a good idea. I assume that you have downloaded both codeigniter and ZF2. Help on installing Zend Framework 2 in ubuntu can be found here.

Now as the two frameworks are downloaded, copy the Zend folder(under library) from Zend download to application/libraries in Codeigniter. The idea here is to use the Zend components as a library in Codeigniter. Lets see an example of using Zend Captcha in Codeigniter.

First we need to create a new file under application/libraries, lets call it "Zend". After creating this file and open it in a text editor and copy paste the following code:

Zend.php

require_once 'autoload.php';
class Zend{

public $obj;
public $objId;

public function __construct(){

}


public function createImageCaptcha($params=array()){
$this->obj = new Zend\Captcha\Image( array(
  'imgDir'=>'public/',
  'font' => 'font/opensans-regular-webfont.ttf',
  'width' => 250,
  'height' => 100,
  'dotNoiseLevel' => 40,
  'lineNoiseLevel' => 3)
);
$this->obj->generate();
return $this->obj;
}

}


In the constructor i am just including the corresponding class file from Zend. The function createImageCaptcha() actually creates an image of type png inside the path you specify, imgDir variable sets the file path and font variable sets the font path. Remember that the paths are relative your root folder. Here what i am trying to do is to create my own wrapper to the Zend components instead of calling them directly in controller. In my controller i would access my Zend Captcha as follows:

$this->load->library('zend');
$captcha = $this->zend->createImageCaptcha();


Here $captcha is an object and will hold all the information regarding the Captcha.  $captcha->getimgDir()  would give you the image directory, $captcha->getId() would give you the filename, $captcha->getsuffix() would give you the file extension and so on. All the properties can be accessed by just appending "get" to them. 

At last but not least we need to know about the file named "autoload.php" which is included in the top. The purpose of this file is to autoload all the dependency files in Zend while instantiating an object. If this file is not present then an error like the following may appear "Fatal error: Class 'Zend\Captcha\AbstractWord' not found", in case of Captcha component. Same  will be the case with all components in Zend. So instead of updating every file with include directive we autoload all the dependent files. 

autoload.php

namespace Zend;
spl_autoload_register(function ($class) {
    if (substr($class, 0, strlen(__NAMESPACE__)) != __NAMESPACE__) {
        //Only autoload libraries from this package
        return;
    }
    $path = substr(str_replace('\\', '/', $class), 0);
    $path = __DIR__ . "/".$path . '.php';
    if (file_exists($path)) {
        require $path;
    }

});

The main purpose of this article is to explain how to use ZF2 modules along with Codeigniter. Hope this article was helpfull. If you find this information incorrect please don't hesitate to comment. There is also an alternative by using the third_party option in Codeigniter. 


Wednesday, October 9, 2013

Twitter codeigniter-php library

I have created a Codeigniter library and a helper that would fetch the tweets from a twitter account and display it. You can find it here. The usage of this library is simple.
in your controller file just add the following to get the tweets.


   $params = array(
'userName'=>'your name',
'consumerKey'=>'your consumer key',
'consumerSecret'=>'your secret',
'accessToken'=>'your access token',
'accessTokenSecret'=>'your access token secret',
'tweetLimit'=>5,// the no of tweets to be displayed
);
$this->load->library('twitter',$params);
$tweets = $this->twitter->getHomeTimeLine();
$this->load->helper('tweet');
$mytweets = getTweetsHTML($tweets);
                echo $mytweets;

preventDefault not working in IE

Just change the event.preventDefault() to the following.

if(event.preventDefault){ event.preventDefault(); }
else { event.returnValue = false; }

eg :
    $(document).ready(function(){
           $('#myControl').click(function(e){
                   if(e.preventDefault){ e.preventDefault(); }
                   else { e.returnValue = false; }
           });
    });

Installing zend framework 2 in ubuntu

There are a lot of resources available on Zend framework, but almost all of them are focused for experienced developers. I am writing this article so that a beginner can install the new Zend Framework 2 and start experimenting on it. The following are the steps that will let you achieve this:
Step 1: Create a directory under your web root. Lets say the folder name is "MyZendProject".
Step 2: Open Terminal and select the newly created directory(eg: cd /var/www/MyZendProject).
Step 3: Now type the following command in terminal
git clone git://github.com/zendframework/ZendSkeletonApplication.git and press enter.
This will install the Zend frameworks skeleton application in your computer. If git is not present, then you can simply install git by typing the following command in terminal
sudo apt-get install git and press enter.

Step 4:Once the skeleton application is downloaded in your folder you will find the composer.phar php file inside ZendSkeletonApplication folder. Just copy all the files inside this newly created folder to your folder. i.e from MyZendProject/ZendSkeletonApplication toMyZendProject. Our next job is to run the composer.phar file.

Step 5:In terminal type php composer.phar self-update and press enter.
Step 6: In terminal type php composer.pharinstall and press enter.
That's it. it's all done. Now open your browser and navigate to your http://localhost/MyZendProject/public/.
You can also download the Zend documentation from here

Please don't hesitate to comment if any problems occurs while performing these steps. Enjoy!!!.