Friday, 25 December 2015

How to implement SASS in Laravel 5.1 (with pure PHP)

Hi Everybody,

In this blog we will discuss about how to implement SASS in Laravel 5.1

This is a super-simple PHP script – loaded via Composer – that compiles your SASS stuff to CSS every time you run your application (while in development for sure).

It’s extremely simple (one line of code in a default setup), and built on top of the excellent scssphp SASS compiler, a tool that does exactly what Ruby’s SASS compiler does, but it is written in pure PHP. And by the way, it also works with any other modern PHP-framework too, you’ll just have to edit the folder paths.

This will compile your entire SASS files to CSS every X seconds. A little bit weird, but in the beginning I thought this might be the better solution.

For this tutorial we assume you already have Laravel installed and running.

The installation


Add this to your composer.json, please note that this is a require-dev, not a normal require. This devides real dependencies from ones you only need for local development.

"require-dev": {
    "panique/laravel-sass": "dev-master"
}

Then edit your index.php (in folder “public”) and put this line right before $app->run().

SassCompiler::run("scss/", "css/");
// some people said this does not work in their installation, so if you have trouble, try these paths:
// SassCompiler::run("public/scss/", "public/css/");

The first parameter is the folder where your SASS files are, the second one if the folder where your CSS are or should be. If you don’t have these folder, create them. Also make sure PHP has write-rights to the css folder, so do a

sudo chmod -R 777 public/css

while being in var/www. Please note that this is just for development, on a production server we don’t need the css folder to be writeable in any way.

Now install the Composer dependencies via

composer install
or
composer update

Composer automatically installs everything in require and require-dev by default.

Now edit app/views/hello.php and put something like

<link rel="stylesheet" type="text/css" href="css/style.css">

into the head to make sure we really load a .css file. Also delete the entire default style block (so it don’t confuses you in any way).

Create a style.scss in public/scss and put some basic SASS rules in it, like

$color_one: green;
$color_two: yellow;

body {
    background-color: $color_one;
    .welcome {
        background-color: $color_two;
    }
}

and run your app. You should instantly see the startscreen with weird colour, defined by the above SASS file.

In production

When going to production, make sure you install your Composer dependencies without the stuff defined in require-dev (which is just for development purposes), via

composer install --no-dev

Also make sure to comment out the new line in your index.php Future version of the script will contain a development / production switch that doesn’t need manual actions.

Thanks!!!

Friday, 18 December 2015

How to implement asynchronous processes in PHP

Hi Everybody,

In this blog we will discuss about how to implement asynchronous processes in PHP.

There's certainly more than one way to skin asynchronous tasks in PHP.

One of the main reasons we need asynchronous processes in PHP is to allow something very time consuming to happen in the background, but not keep the client “on hold” for that entire duration; as PHP is typically synchronous, anything that takes a long time on the server will appear to take a long time for the client.

In that scenario, one solution would be to “detach” the client from the currently loading page, and let them have control of their browser back while the PHP script continues to do it's thing. We should be able to make this happen by sending some headers to the client to say “ok, we’re done here, connection ends”, even though PHP is still running.


class Service
{
    const HEADER_NEW_LINE = "\r\n";

    public function store()
    {
        /*code for reduce process time*/
        self::closeConnection('true');
//do your code that take much more time e.g. upload a video or import an excel that take more time
    }

    public static function closeConnection($instantOutput = '') {
        set_time_limit(0);
        ignore_user_abort(TRUE);
        header('Connection: close' . self::HEADER_NEW_LINE);
        header('Content-Encoding: none' . self::HEADER_NEW_LINE);
        ob_start();
        echo $instantOutput;
        $size = ob_get_length();
        header('Content-Length: ' . $size, TRUE);
        ob_end_flush();
        ob_flush();
        flush();
    }
}

There are another way to implement asynchronous in php like open socket, log file, fork a curl process etc, but as per my requirement i did choose this 'detach client' method, you are free to choose any method as per your requirement.

Thanks.



Friday, 4 December 2015

How to generate a Certificate Signing Request (CSR) - Apache 2.x

Hi Everybody,

Today we will discuss about how to generate a Certificate Signing Request (CSR) for Apache 2.x web server.

Follow these instructions to generate a certificate signing request (CSR) for your Apache Web server. When you have completed generating your CSR, cut/copy and paste it into the CSR field on the SSL certificate-request page.
To Generate a Certificate Signing Request for Apache 2.x

1. Log in to your server's terminal (SSH).

    At the prompt, type the following command:
    openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.key -out yourdomain.csr

    Replace yourdomain with the domain name you're securing. For example, if your domain name is       coolexample.com, you would type coolexample.key and coolexample.csr.
    

2. Enter the requested information:

     2.1.  Common Name: The fully-qualified domain name, or URL, you're securing.
        If you are requesting a Wildcard certificate, add an asterisk (*) to the left of the common name where you want the wildcard, for example *.coolexample.com.
     2.2.  Organization: The legally-registered name for your business. If you are enrolling as an individual, enter the certificate requestor's name.
     2.3.  Organization Unit: If applicable, enter the DBA (doing business as) name.
     2.4.  City or Locality: Name of the city where your organization is registered/located. Do not abbreviate.
     2.5  State or Province: Name of the state or province where your organization is located. Do not abbreviate.
     2.6. Country: The two-letter International Organization for Standardization (ISO) format country code for where your organization is legally registered.

        If you do not want to enter a password for this SSL, you can leave the Passphrase field blank. However, please understand there might be additional risks.

3. Open the CSR in a text editor and copy all of the text.

    Paste the full CSR into the SSL enrollment form in your account.

Thanks.

Friday, 27 November 2015

Add extra field in migration after creating table in Laravel 5.1

Hi Everybody,

In this blog we will discuss about how to add an extra field in migration after creating a table.

First time we create a table's migration & execute migration command. After this , we realize that we have to add a new field in database.

For this, we can modify table by this easy way.

Firstly run this command for create a new migration file.


php artisan make:migration add_fb_id_in_users_table

It will create a new file in migration file. Write in its up() function the following lines.

 Schema::table('users', function ($table) {
            $table->string('fb_id');
          });


and in down() function write the following lines:

Schema::table('users', function ($table) {
            $table->drop_column('fb_id');
          });


Make sure you put the same table name which you want to edit.

Now run migration command for this file.

php artisan migrate

Thanks.

Friday, 20 November 2015

How to crop image with jquery and php

Hi Everybody,

Today I am going to write this tutorial how to crop images with jQuery and PHP. I have used jCrop JavaScript library to perform this task with PHP its a very easy to implement and very useful for thumbnail generation. Hope you love this tutorial.

Requirement

Download the current version of Jcrop
Place the files on your web server so you can request them from your page
You also must have jQuery installed and included!

PHP Methods to save image:

crop.php

<?php
$targ_w = $targ_h = 150;
$jpeg_quality = 90;

$src = 'demo_files/pool.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

imagecopyresampled($dst_r,$img_r,0,0,$_POST['imgX1'],$_POST['imgY1'],
$targ_w,$targ_h,$_POST['imgWidth'],$_POST['imgHeight']);

header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
?>

This will simply show image on crop if you want to save that image in some directory then make changes in last two line as below.

//header('Content-type: image/jpeg');
imagejpeg($dst_r,PATH_TO_SAVE_IMAGE,$jpeg_quality);


Html JavaScript Configurations:

write below html after php code in crop.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>Live Cropping Demo</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<script src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript">
    $(function(){
    $(\'#cropbox\').Jcrop({
    aspectRatio: 1,
    onSelect: SetCoordinates,
//    minSize:[200,200], start minimum image size
//    maxSize:[200,200], max size should be...
    });
});

function SetCoordinates(c) {
    $('#imgX1').val(c.x);
    $('#imgY1').val(c.y);
    $('#imgWidth').val(c.w);
    $('#imgHeight').val(c.h);
    showPreview(c);
}

function showPreview(coords)
{
var rx = 100 / coords.w;
var ry = 100 / coords.h;

$('#preview').css({
width: Math.round(rx * 500) + 'px',
height: Math.round(ry * 370) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
</script>
</head>
<body>

<form action="crop.php" method="post">
<div class="modal-body text-center" >
<div><img src="demo_files/pool.jpg" id="cropbox"/></div>
<div style="width: 405px; height: 200px;" id="preview"><img src="demo_files/sago.jpg" style="display:'none'"/>
</div>
<div class="clearfix"></div>
<div class="modal-footer">
<input type="submit" id="btnCrop"  class="btn btn-success" value="Crop"/>
<input type="button" id="btnUpload" class="btn btn-failure" value="Cancel"/>
<input type="hidden" name="PicimgX1" id="PicimgX1" />
<input type="hidden" name="PicimgY1" id="PicimgY1" />
<input type="hidden" name="PicimgWidth" id="PicimgWidth" />
<input type="hidden" name="PicimgHeight" id="PicimgHeight" />
</div>
</form>
</body>
</html>

If you face any problem feel free to post your doubt or suggestion in comment box.
Thanks

Friday, 13 November 2015

Managing markers with the Same Coordinates in a Google Map

Hi Everybody,

In this blog we will discuss about managing multiple markers with the exact same location.
Google Maps API is an awesome tool, even though it has enough cons to hate it, it still has more pros to enjoy. In 3d revision of the API Google introduced new feature called clusters, which allows you to unite multiple markers in certain location and display a cluster instead, with a number of places it includes. Clicking on a cluster leads to zooming in, which reveals hidden markers and cluster disappears.

It works great, although there is an issue which is not covered by the library yet. When you have multiple markers with the exact same location, no matter how deep you zoom in, you won’t get a chance to see markers. If you remove clustering on a certain zoom levels (or remove it at all), you’ll see only one marker there(the top one), others will remain hidden underneath, since they stack on top of each other.

Solution


I’ve found couple of solutions out there in the web, but this one works best for me so far.

The idea is to iteratively check if existing markers match the coordinates of the new marker, if some of them do – than we add an offset to their coordinates.

I assume you already have a working application, which uses Google Maps API.

In your createMarker function add this code:

function createMarker(number, address, lat, lng) {
    var contentString = address;
    var newLat = lat + (Math.random() -.5) / 1500;// * (Math.random() * (max - min) + min);

    var newLng = lng + (Math.random() -.5) / 1500;// * (Math.random() * (max - min) + min);
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(newLatnewLng),
        map: map,
        icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+number+'|FF0000|000000'
    });

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent(contentString);
        infowindow.open(map, marker);
    });
    bounds.extend(marker.position);
}

(Math.random() -.5) / 1500 is about 100m, feel free to tweak an offset however you want.

    (Math.random() -.5) / 750 ~ 50m
    (Math.random() -.5) / 3000 ~ 200m

Note:-It’s not the cleanest solution, since your slightly corrupt data and some applications simply can’t afford it. I’d like to do this later on, but for a quick fix this solution will work just fine.

Friday, 6 November 2015

How to set custom image and label of marker on google map using jquery

Hi Everybody,

First of all wish you a very happy Diwali.

In this blog we will discuss how to set custom image and label of marker on google map using Jquery.

Html and css code

<html>
<head>
  html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
   .labels {
     color: white;
     background-color: red;
     font-family: "Lucida Grande", "Arial", sans-serif;
     font-size: 10px;
     text-align: center;
     white-space: nowrap;
   }
</head>
    <title>Simple Map</title>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.9/src/markerwithlabel.js"></script>
  <body>
    <div id="map-canvas"></div>
  </body>
      

Jquery Code

  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

var marker = new MarkerWithLabel({
       position: new google.maps.LatLng(-34.397, 151.244),
       map: map,
       icon: "https://maps.gstatic.com/mapfiles/ms2/micons/marina.png",
       draggable: true,
       raiseOnDrag: true,
       labelContent: "1",
       labelAnchor: new google.maps.Point(-5, 35),
       labelClass: "labels", // the CSS class for the label
       labelInBackground: false
});

Output



If you face any problem in implement this, feel free to post your doubt in comment section.