Friday, May 8, 2015

Easy & Secure client side form validation using jquery validation plugin.

Jquery Validation Plugin:

This is very easy and secure method for client side form validation using validation plugin.

For this you have to include these three jquery validation libraries.

1. First
2. Second
3. Third

After this in your <script> you will add this:


<script>
    $(document).ready(function () {
        $('#myForm').validate({
            ignore: [],
            rules: {
                filename: {
                    required: true,
                    extension: 'docx|doc|gif|jpg|jpeg|png|pdf'                }
              },
            submitHandler: function(form) {
                $('#myForm')[0].submit();
                return false;
            }
        });
    });
</script>

<form method="post" action="/create2" id="myForm" enctype="multipart/form-data">
 <input type="file" name="filename" class="form-control"/>
 <label for="filename" class="error" style="display:none;color:red">This field is required</label> 
 <input type="submit" class="btn btn-primary" id="submit" name="submit" value="submit">
</form>

This will validate your file as required & its extension format.
 Also, you can add filesize in it according to your need.

Thanks

Friday, April 17, 2015

How to save a form in Yii Framework

Save Form in Yii Framework:

Create a create.php in view part & add this :

<?php
$form = $this->beginWidget('CActiveForm', array(
    'id' => 'space-create-form',
    'enableAjaxValidation' => false,
    'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<div class="form-group">
    <label><?php echo Yii::t('SpaceModule.views_create_create', 'Project Name'); ?></label>
    <?php print $form->textField($model, 'name', array('class' => 'form-control', 'placeholder' => Yii::t('SpaceModule.views_create_create', 'project titan'))); ?>
    <?php echo $form->error($model, 'name'); ?>
</div>
<div class="form-group">
    <label><?php echo Yii::t('SpaceModule.views_create_create', 'Business Founded'); ?></label>
    <?php print $form->textField($model, 'business', array('class' => 'form-control', 'placeholder' => Yii::t('SpaceModule.views_create_create', 'business founded'))); ?>
</div>
<?php
echo HHtml::ajaxButton(Yii::t('SpaceModule.views_create_create', 'Create'), array('//space/create/create'), array(
    'type' => 'POST',
    'beforeSend' => 'function(){ setModalLoader(); }',
    'success' => 'function(html){ $("#globalModal").html(html); }',
), array('class' => 'btn btn-primary', 'id' => 'space-create-submit-button'));
?>


In your Create Controller:

public function actionCreate()
{
if (!Yii::app()->user->canCreateSpace()) {
    throw new CHttpException(400, 'You are not allowed to create spaces!');
}
$model = new Space('edit');

// Ajax Validation
if (isset($_POST['ajax']) && $_POST['ajax'] === 'space-create-form') {
    echo CActiveForm::validate($model);
    Yii::app()->end();
}

if (isset($_POST['Space'])) {

    $_POST['Space'] = Yii::app()->input->stripClean($_POST['Space']);

    $model->attributes = $_POST['Space'];
    if ($model->validate() && $model->save()) {

        // Save in this user variable, that the workspace was new created
        Yii::app()->user->setState('ws', 'created');
        // Redirect to the new created Space
        $this->htmlRedirect($model->getUrl());
    }
}

$this->renderPartial('create', array('model' => $model), false, true);
}


In your space modal:

Firstly add your attributes in attributeLabels() function

public function attributeLabels()
{
    return array(
        'name' => Yii::t('SpaceModule.models_Space', 'Name'),
        'business' => Yii::t('SpaceModule.models_Space', 'Business Founded'),
)};


Also, add in your rules();

public function rules()
{
    $rules = array();
    if ($this->scenario == 'edit') {
        $rules = array(
            array('name,business', 'safe'),
        );
        }
        return $rules;
   }



*You must have to add in your rules(), Otherwise it will show xss errors.

Thanks

Friday, April 10, 2015

How to redirect of any url in Nginx to any another IP address of Apache2 server with same URL(proxy & reverse proxy pass)?

Redirect nginx url to apache2 ip address:

I have a website xyz.com on nginx server & any another website  xxx.xxx.xxx.xxx on apache2 server. Now i want to proxy pass xyz.com/hello to my ip address & also reverse proxy from my ip address. So, that my ip address will show on "xyz.com/hello"  this url.

For this:

Add in your nginx configuration:

location /hello {
                    proxy_pass http://xxx.xxx.xxx.xxx;
                  }


This will directly redirect  xyz.com/hello & xyz.com/hello/ to ip address xxx.xxx.xxx.xxx

Now come to apache2 configuration:

In case of wordpress set your .htaccess file

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>


Also, set in wordpress admin panel's setting

WordPress Address (URL) :  http://xxx.xxx.xxx.xxx
Site Address (URL) : http://xyz.com/hello

Or  you can do it with any another way if you are not using wordpress or any another CMS.

Now your apache2 website xxx.xxx.xxx.xxx will be work on this url http://xyz.com/hello

Thanks.

Friday, March 27, 2015

Draw map route b/w two points in php using google map api

Draw Map Route:

Pre-Requirement:- Installed PHP and web server as well JQuery working in your project.

Step 1:- Include <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.17&sensor=false"></script> in your view where you want to show map.

Step 2:- In your controller get the points in between we want to create road map route. Let the vars are $start(exp Delhi=28.6100,77.2300) and $end(exp Mumbai=18.9750,72.8258).

Step 3:-In view include the below script after the file is included

<script type="text/javascript">
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  function initialize(start,end) {
    var latlng = new google.maps.LatLng(start);
    directionsDisplay = new google.maps.DirectionsRenderer();
calcRoute();
    var myOptions = {
      zoom: 14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    var marker = new google.maps.Marker({
      position: latlng,
      map: map,
      title:"My location"
    });
  }
  function calcRoute(start,end) {
    var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
</script>

Step 4:- In view take the values in hidden input fields as follows

<input type="hidden" name="start_pt" id="start_pt" value="<?php echo $start; ?>"/>
<input type="hidden" name="end_pt" id="end_pt" value="<?php echo $end; ?>"/>

Step 5:- At the end of the file include the script as follows

    <script>
      window.onload = initialize($('#start_pt').val(),$('#end_pt').val());
    </script>

Step 6:-At the end don't forgot to include the div where you want to show the map with your desired dimentions

<div id="map_canvas" style="width:710px; height:300px"></div>

Friday, March 20, 2015

How to send notification to android phone using php?

Send Notification in php:

It's very easy way to send notification to a android phone in php.

Firstly we have to register on Google Cloud Messaging  using its steps.

You'll get a api key due do doing all the steps.

One more thing you have to do , just find your device token of your android phone and that's it. Use the following code and you'll get a sure notification

            $ids = array($deviceToken);
            $apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
            $url = 'https://android.googleapis.com/gcm/send';

            $message = json_encode(
                array(
                    'registration_ids' => $ids,
                    'data' => $sendData
                )
            );
            $headers = array(
                'Authorization: key=' . $apiKey,
                'Content-Type: application/json'
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
            $result = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'GCM error: ' . curl_error($ch);
            }
            curl_close($ch);


Thanks

Friday, March 13, 2015

Redis in Laravel

Redis in Laravel:

Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, and sorted sets.

Configuration:

The Redis configuration for your application is stored in the app/config/database.php file. Within this file, you will see a redis array containing the Redis servers used by your application:

'redis' => array(

    'cluster' => true,

    'default' => array('host' => '127.0.0.1', 'port' => 6379),

),

Usage:

$redis = Redis::connection();
$redis = Redis::connection('other');
$redis->set('name', 'Taylor');

$name = $redis->get('name');

$values = $redis->lrange('names', 5, 10);
$values = $redis->command('lrange', array(5, 10));
Redis::set('name', 'Taylor');

$name = Redis::get('name');

$values = Redis::lrange('names', 5, 10);    

Thanks

Friday, February 27, 2015

Easy way to send notification on iPhone in php

Notification on iPhone:

This is very easy & effective way in php to send a notification on your iPhone.

For this you will be in need of three things.

1. Your iPhone's device token
2. .pem file for iPhone
3. Its passphrase.

For tihs use the following code.

        $deviceToken = 'enter_your_device_token';
        $passphrase = 'enter_your_passphrase';
        $message = 'enter_your_notification_message';

        $badge = 1;
        $ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', 'path_to_pem_file.pem');
        stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

        // Open a connection to the APNS server
        $fp = stream_socket_client(
            'ssl://gateway.sandbox.push.apple.com:2195', $err,
            $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
        if (!$fp)
            exit("Failed to connect: $err $errstr" . PHP_EOL);
        echo 'Connected to APNS' . PHP_EOL;

        // Create the payload body
        $body['aps'] = array(
            'alert' => $message,
            'badge' => $badge,
            'sound' => 'newMessage.wav'
        );

        // Encode the payload as JSON
        $payload = json_encode($body);

        // Build the binary notification
        $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

        // Send it to the server
        $result = fwrite($fp, $msg, strlen($msg));

        if (!$result)
            echo 'Error, notification not sent' . PHP_EOL;
        else
            echo 'notification sent!' . PHP_EOL;

        // Close the connection to the server
        fclose($fp);


Thanks.