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.

Friday 30 October 2015

How to calculate latitude and longitude for a given address and vise-versa in php

Hi Everybody,

In this blog we will discuss about how to calculate latitude and longitude for a given address and vise-versa in php.

Get latitude and longitude from a  given address(Geocode):-


        $address = "790 Castro St, Mountain View, CA";

        $formAddr = str_replace(' ','+',$address);

        $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formAddr.'&sensor=false');

        $output= json_decode($geocode);

        if(is_array($output )&& $output ['Status']['code']==200) {

                    $latitude = $output->results[0]->geometry->location->lat;

                    $longitude = $output->results[0]->geometry->location->lng;

       }

Get address from latitude and longitude(Reverse Geocode):-


       $lat = 37.3874353;
        $lng = -122.0835459;
        $revGeocode = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false");
        $output = json_decode($revGeocode);
        if(is_array($output )&& $output ['Status']['code']==200) {
                    $address = $output->results[0]->formatted_address;
        }

Let me know if you face any problem in this.
Thanks.

Friday 23 October 2015

How to change format of mobile number in US format (XXX) XXX-XXXX using Jquery

Hi Everybody,

In this blog we will discuss about how to change format of mobile number in US format (XXX) XXX-XXXX using Jquery.

For this we have to code our Html and Jquery, given below

Html Code


<form id="example-form" name="my-form">
    <label>Phone number:</label><br />
    <!-- I used an input type of text here so browsers like Chrome do not display the spin box -->
    <input id="phone-number" name="phone-number" type="text" maxlength="14" placeholder="(XXX) XXX-XXXX" /><br /><br />
    <input type="button" value="Submit" />
</form>

Jquery Code

$('#phone-number', '#example-form')

.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);

// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}

// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 || 
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});

Note:-After change mobile number in this format, best practice is this you have to save only 10 digit mobile number in your database(without (, ), and space).

For this if your server side script written in php then use below code to convert this US format mobile number to simple 10 digit number(for save in database) .

PHP Code

preg_replace("/[^0-9]/","",$mobile)

here $mobile is mobile input field you receive by Get or Post method after submit this form.

Thanks for read this blog, if you any question or suggestion please type in comment box.

Friday 16 October 2015

Auto populate city and state using zip code(USA) in Laravel 5.1

Hi Everybody,

In this blog we will discuss how to auto populate USA city and state using zip code in Laravel 5.1.
For this we have to use google api for find city and state using zip code.

1. Routes


routes.php
Route::post('get/citystate', 'CityStateController@getCityState');

2. Controller

CityStateController.php

<?php

namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;

class AccountController extends Controller
{
 public function getCityState($blnUSA = true) {
        $data = Input::all();
        $zip = $data['zip'];
        $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";
        $address_info = file_get_contents($url);
        $json = json_decode($address_info);
        $city = "";
        $state = "";
        $country = "";
        $arrReturn = array();
        if (count($json->results) > 0) {
            //break up the components
            $arrComponents = $json->results[0]->address_components;

            foreach($arrComponents as $index=>$component) {
                $type = $component->types[0];

                if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                    $city = trim($component->long_name);
                }
                if ($state == "" && $type=="administrative_area_level_1") {
                    $state = trim($component->short_name);
                }
                if ($country == "" && $type=="country") {
                    $country = trim($component->short_name);

                    if ($blnUSA && $country!="US") {
                        $city = "";
                        $state = "";
                        break;
                    }
                }
                if ($city != "" && $state != "" && $country != "") {
                    //we're done
                    break;
                }
            }
        }
        return $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);
    }

}

3. View

citystate.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery.js"></script>
<script>

function is_int(value){
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
        return true;
    } else {
        $("#city").val(''); /* Fill the data */
        $("#state").val('');
        return false;
    }
}

$("#zip").keyup(function() {
    $(".zip-error").hide(); /* In case they failed once before */
    var el = $(this);
    if ((el.val().length == 5) && (is_int(el.val()))) {
        $.ajax({
            url: '/get/citystate',
            type: "POST",
            data: "zip=" + el.val(),
            success: function(result, success) {
                $("#city").val(result['city']); /* Fill the data */
                $("#state").val(result['state']);
                if($("#city").val()=="" || $("#state").val()==""){
                    $(".zip-error").show(); /* Ruh row */
                }else{
                    $(".zip-error").hide(); /* In case they failed once before */
                }
            },
            error: function(result, success) {
                $(".zip-error").show(); /* Ruh row */
            }
        });
    }else{
        $(".zip-error").show(); /* Ruh row */
    }
});
</script>
</head>
<body>
<div class="container">
<div class="form-group">
<div class="row">
    <div class="col-md-4 mrgn_t_10">
        <input type="text" pattern="[0-9]*"  maxlength="5" class="form-control indent_zero" id="zip" placeholder="ZIP" name="zip" value=""><p class="zip-error" style="display: none">Not a real zip code.</p></div>

  <div class="col-md-4 mrgn_t_10">
  <input type="text" class="form-control indent_zero" id="city" placeholder="CITY" name="city" value=""></div>
  
  <div class="col-md-4 mrgn_t_10">
      <input type="text" class="form-control indent_zero" id="state" placeholder="STATE" name="state" value=""></div>
</div>
</div>
</div>
</body>
</html>

If you have any query you can post it in comment.
Thanks.

Friday 9 October 2015

How does Upgrading PHP Solve Security Issues?

Hi Everybody,

In this blog we will discuss about security in PHP.

PHP is a popular language and has been more accepted than any other as the platform of choice for the web. PHP has evolved that it is now the run time environment backing many of the world’s highest traffic web sites and largest open source projects such as Drupal, Magento and Wordpress.

But as dependent these businesses are on PHP,  they constantly resist adoption of newer versions. They see adoption and change as a risk to losing their market share and end-user trust. It is a struggle leading to a history making security threat to today's web.

It Starts with Awareness

Many talk about writing secure PHP code. But not much information is written about why upgrading PHP versions makes web applications more secure. The first step is to be aware of the security vulnerabilities.

Threat Types

DoS  -  In a denial-of-service DoS attack, an attacker attempts to prevent legitimate users from accessing information or services. By targeting a computer and its network connection or other services that rely on the affected computer. Sometimes the attacker can inject and execute arbitrary code while performing a DoS attack in order to access critical information or execute commands on the server.

Code Execution  - an attacker's ability to execute any commands of the attacker's choice on a target machine or in a target process. It is the most powerful effect a bug can have because it allows an attacker to completely take over the vulnerable process. From there the attacker can potentially take complete control over the machine the process is running on.

Overflow  - more commonly known as stack overflows occur when variable size data is copied into fixed length buffers located on the program stack without any bounds checking. Vulnerabilities of this class are generally considered to be of high severity since their exploitation would mostly permit arbitrary code execution or Denial of Service. Rarely found in interpreted platforms, code written in C and similar languages is often ridden with instances of this vulnerability.

Memory Corruption  -  Using memory beyond the memory that was allocated buffer overflow. If an array is used in a loop, with incorrect terminating condition, memory beyond the array bounds may be accidentally manipulated. Buffer overflow is one of the most common programming flaws exploited by computer viruses.

Sql Injection - SQL Injection is one of the many web attack mechanisms used by hackers to steal data from organizations. It is perhaps one of the most common application layer attack techniques used today. It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.  

XSS  -   Cross-site Scripting (XSS) refers to client-side code injection attack wherein an attacker can execute malicious scripts (also commonly referred to as a malicious payload) into a legitimate website or web application. XSS is among est the most rampant of web application vulnerabilities and occurs when a web application makes use of invalidated or decoded user input within the output it generates.

Directory Traversal  -  Properly controlling access to web content is crucial for running a secure web server. Directory traversal is an HTTP exploit which allows attackers to access restricted directories and execute commands outside of the web server’s root directory.

HTTP Response Splitting  -   HTTP response splitting occurs when data enters a web application through an untrusted source, most frequently an HTTP request. The data is included in an HTTP response header sent to a web user without being validated for malicious characters.

Bypass something  -  bypass vulnerabilities of authentication, web server limitations or operating system limits are generally caused by programmers assuming that users will behave in a certain way and failing to foresee the consequences of users doing the unexpected.

Gain Information - Intruders may be able to gain access to specific information stored on the host, including security settings. This could result in potential misuse of the host by intruders.  

Gain Privileges  - Privilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. The result is that an application with more privileges than intended by the application developer or system administrator can perform unauthorized actions.
CSRF - Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF (sometimes pronounced sea-surf) or XSRF, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts.

File Inclusion - File inclusion vulnerability is a type of vulnerability most often found on websites. It allows an attacker to include a file, usually through a script on the web server.

Multiple Exploitation Fronts

Being aware of the types of threat is not enough. What many don't  realize is a security threat can take on place on multiple fronts. They can be independent or interdependent.

This is one of the facts that many open source projects miss. They assume that once a piece of code is patched then the security problem has been removed forever. Not recognizing that it still remains but only has been obstructed by a re-factoring of a singularly obvious instance. A threat can re-occur over time through code base changes. In a project with  thousands of contributors both core and third-party. The chances of the same exploit being written into the code base several times over is extremely high.

Web Server - A web server is an information technology that processes requests via HTTP, the basic network protocol used to distribute information on the World Wide Web. The term can refer either to the entire computer system, an appliance, or specifically to the software that accepts and supervises the HTTP requests.

Server Operating System - The operating system is the most important program that runs on a computer. Every general-purpose computer must have an operating system to run other programs and applications. Operating systems perform basic tasks, such as recognizing input from the keyboard, sending output to the display screen, keeping track of files and directories on the disk, and controlling peripheral devices such as disk drives and printers.

Code run-time execution - A run time program is an application that is distributed for use. Code run time environments can be one of  several  interpreters, compilers and virtual machines being the most common.

PHP interpreter

Web Server Vulnerabilities

You can find hundreds of tutorials and best practices for securing PHP on the web server. You'll also find that the popular  web servers like Apache are in a constant state of flux and  newer versions being readily adopted.

There are five vulnerabilities fixed in the latest release of the Apache Web server, including a buffer overflow and several denial-of-service vulnerabilities. Fixes for these flaws have landed in the developer release of the server

This trust in new versions is something that the PHP interpreter does not enjoy.
There are five vulnerabilities fixed in the latest release of the Apache Web server, including a buffer overflow and several denial-of-service vulnerabilities. Fixes for these flaws have landed in the developer release of the server, 2.4.10-dev.

Code Vulnerabilities

The big three CMS are constantly pushing for users to upgrade to close security holes allowed in code. They create message applications designed for upgrading extensions. They have mailing lists with subscribers numbering in the thousands.  All dedicated to maintaining security within this area.


PHP Interpreter Vulnerabilities

This is the area where information is weak. Where upgrading PHP can increase security by removing an exploitation front. decreasing threat levels in others. Because in the first categories there are hundreds of developers and bloggers  pointing fingers at  the other items. Yet they never mention upgrading the PHP version that also might be responsible for making the exploit possible.  One might suppose they either assume version upgrades or don't care.

Honestly, I think that the largest failure in this area is hubris. Developers and DevOps can show-off their intelligence with knowledge of code and server security. But they are well aware of the fact that version upgrades can break many things and make them look bad.

Even in the face of a warning upgrading PHP will be delayed and hopefully the responsibility can be handed off to the web hosting company. The  hosting company on the other side is of course waiting for a catastrophe or land slide of complaints before acting.  The resulting  stalemate of inaction is what hackers count on for access.

A newly reported critical vulnerability in PHP enables would-be cyber criminals to steal source code or inject and run malware in PHP applications by adding command-line parameters to URLs. Fortunately, The PHP Group has announced updates to PHP that its says eliminates the vulnerability.

The hosting company might make a newer version of PHP available but they will not enforce it's use.  In the mean time script kiddie bots are searching for sites to exploit.



The state of PHP Security

Note  that the year of 2007 was very high in vulnerabilities and also was the slowest adoption rate of a new version of PHP. One only has to extrapolate to see that the increase in threats was due to less secure versions remaining available for an overly long period.

When you don't  take in account the upgrading of PHP into your security efforts then you are pouring them into a leaky bucket. It's is only a matter of time before a widespread threat event. Imagine if your code is a major player in supporting the 30% or so of websites that use a CMS.




Friday 25 September 2015

Add extra field in migration after creating table in Laravel 5.1

Hi Everybody,

In this blog we will discuss about add extra field in migration after creating 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_email_in_users_details_table


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

        Schema::create('user_details', function ($table) {
            $table->string('email');
          });

and in down() function write the following lines:

Schema::create('user_details', function ($table) {
            $table->drop_column('email');
          });

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 18 September 2015

How to build a web calendar in Laravel 5.1

Hi Everybody


Calendar is a very common element in today's web applications. Whether you are building an event booking application, appointment system or even a social network. Calendar is essential.
In this tutorial, we go through steps of building a calendar in Laravel 5.1.

After this tutorial, hopefully you will understand the concepts of building calendar and use the calendar script in your own application.

1. Building the Calendar route


   in routes.php

 Route::get('/calendar', 'CalendarController@getCalendar');

2. Building the calendar controller


  In controller /app/Http/Controllers/CalendarController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Input;
use App\Calendar;
use URL;

class CalendarController extends Controller
{

public function getCalendar()
    {
        $month = isset($_GET['month']) && !empty($_GET['month']) ? $_GET['month'] : '';
        $year = isset($_GET['year']) && !empty($_GET['year']) ? $_GET['year'] : '';
        $calendar = new Calendar(URL::to('/') . "/calendar");
        return view('calendar', ['calendar' => $calendar->show()]);
    }
}

3. Building the calendar model


   in model(app/Calendar.php) Calendar.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Calendar extends Model
{
    //
    public function __construct($currentRoute){
-        $this->naviHref = $currentRoute;
    }

    /********************* PROPERTY ********************/
    private $dayLabels = array("Mon","Tue","Wed","Thu","Fri","Sat","Sun");

    private $currentYear=0;

    private $currentMonth=0;

    private $currentDay=0;

    private $currentDate=null;

    private $daysInMonth=0;

    private $naviHref= null;

    /********************* PUBLIC **********************/

    /**
     * print out the calendar
     */
    public function show() {
        $year  = null;

        $month = null;

        if(null==$year&&isset($_GET['year'])){

            $year = $_GET['year'];

        }else if(null==$year){

            $year = date("Y",time());

        }

        if(null==$month&&isset($_GET['month'])){

            $month = $_GET['month'];

        }else if(null==$month){

            $month = date("m",time());

        }

        $this->currentYear=$year;

        $this->currentMonth=$month;

        $this->daysInMonth=$this->_daysInMonth($month,$year);

        $content='<div id="calendar">'.
            '<div class="box">'.
            $this->_createNavi().
            '</div>'.
            '<div class="box-content">'.
            '<ul class="label">'.$this->_createLabels().'</ul>';
        $content.='<div class="clear"></div>';
        $content.='<ul class="dates">';

        $weeksInMonth = $this->_weeksInMonth($month,$year);
        // Create weeks in a month
        for( $i=0; $i<$weeksInMonth; $i++ ){

            //Create days in a week
            for($j=1;$j<=7;$j++){
                $content.=$this->_showDay($i*7+$j);
            }
        }

        $content.='</ul>';

        $content.='<div class="clear"></div>';

        $content.='</div>';

        $content.='</div>';
        return $content;
    }

    /********************* PRIVATE **********************/
    /**
     * create the li element for ul
     */
    private function _showDay($cellNumber){

        if($this->currentDay==0){

            $firstDayOfTheWeek = date('N',strtotime($this->currentYear.'-'.$this->currentMonth.'-01'));

            if(intval($cellNumber) == intval($firstDayOfTheWeek)){

                $this->currentDay=1;

            }
        }

        if( ($this->currentDay!=0)&&($this->currentDay<=$this->daysInMonth) ){

            $this->currentDate = date('Y-m-d',strtotime($this->currentYear.'-'.$this->currentMonth.'-'.($this->currentDay)));

            $cellContent = $this->currentDay;

            $this->currentDay++;

        }else{

            $this->currentDate =null;

            $cellContent=null;
        }


        return '<li id="li-'.$this->currentDate.'" class="'.($cellNumber%7==1?' start ':($cellNumber%7==0?' end ':' ')).
        ($cellContent==null?'mask':'').'">'.$cellContent.'</li>';
    }

    /**
     * create navigation
     */
    private function _createNavi(){

        $nextMonth = $this->currentMonth==12?1:intval($this->currentMonth)+1;

        $nextYear = $this->currentMonth==12?intval($this->currentYear)+1:$this->currentYear;

        $preMonth = $this->currentMonth==1?12:intval($this->currentMonth)-1;

        $preYear = $this->currentMonth==1?intval($this->currentYear)-1:$this->currentYear;

        return
            '<div class="header">'.
            '<a class="prev" href="'.$this->naviHref.'?month='.sprintf('%02d',$preMonth).'&year='.$preYear.'">Prev</a>'.
            '<span class="title">'.date('Y M',strtotime($this->currentYear.'-'.$this->currentMonth.'-1')).'</span>'.
            '<a class="next" href="'.$this->naviHref.'?month='.sprintf("%02d", $nextMonth).'&year='.$nextYear.'">Next</a>'.
            '</div>';
    }

    /**
     * create calendar week labels
     */
    private function _createLabels(){

        $content='';

        foreach($this->dayLabels as $index=>$label){

            $content.='<li class="'.($label==6?'end title':'start title').' title">'.$label.'</li>';

        }

        return $content;
    }



    /**
     * calculate number of weeks in a particular month
     */
    private function _weeksInMonth($month=null,$year=null){

        if( null==($year) ) {
            $year =  date("Y",time());
        }

        if(null==($month)) {
            $month = date("m",time());
        }

        // find number of days in this month
        $daysInMonths = $this->_daysInMonth($month,$year);

        $numOfweeks = ($daysInMonths%7==0?0:1) + intval($daysInMonths/7);

        $monthEndingDay= date('N',strtotime($year.'-'.$month.'-'.$daysInMonths));

        $monthStartDay = date('N',strtotime($year.'-'.$month.'-01'));

        if($monthEndingDay<$monthStartDay){

            $numOfweeks++;

        }

        return $numOfweeks;
    }

    /**
     * calculate number of days in a particular month
     */
    private function _daysInMonth($month=null,$year=null){

        if(null==($year))
            $year =  date("Y",time());

        if(null==($month))
            $month = date("m",time());

        return date('t',strtotime($year.'-'.$month.'-01'));
    }

}

Let us take a look at each function in detail.

3.1. public function show():This is the only public function Calendar has. This function basically calls each private function below to create the HTML calendar interface. 

The basic idea of creating a web calendar is that, firstly it determines how many rows(weeks) to create, and then it loops over the rows and create 7 cells on each row. Meanwhile it puts corresponding day value to the cell according to the day of week (Monday to Sunday). 

Take a closer look at each private function below to understand.

3.2. private function _showDay():This function will determine what value to put to the created cell. It can be empty or numbers.

3.3. private function _createNavi(): This function will create the "Prev" && "Next" navigation buttons on the top of the calendar.

3.4. private function _createLabels(): This function will create labels for the day of week. ( Monday to Sunday). You can update the language string to your own choice. But be cautious. You should not change the order of the labels.

3.5. private function _weeksInMonth(): This is a tricky function. It can tell you how many weeks are there for a given month. This is used in show() function to create number of rows(weeks).

3.6. private function _daysInMonth(); This function tells how many days in a given month.
Functions are working closely to create the PHP calendar. You should follow function show() to understand deeply how exactly they call each. Code is documented. Give yourself some time to read it.

4. Make it prettier


Now the Calendar class is actually ready. 
However it looks messy without some CSS tricks. Let us create a CSS file "public/css/calendar.css" to make the calendar look pretty.

/*******************************Calendar Top Navigation*********************************/
div#calendar{
  margin:0px auto;
  padding:0px;
  width: 602px;
  font-family:Helvetica, "Times New Roman", Times, serif;
}
div#calendar div.box{
    position:relative;
    top:0px;
    left:0px;
    width:100%;
    height:40px;
    background-color:   #787878 ;      
}
div#calendar div.header{
    line-height:40px;  
    vertical-align:middle;
    position:absolute;
    left:11px;
    top:0px;
    width:582px;
    height:40px;   
    text-align:center;
}
div#calendar div.header a.prev,div#calendar div.header a.next{ 
    position:absolute;
    top:0px;   
    height: 17px;
    display:block;
    cursor:pointer;
    text-decoration:none;
    color:#FFF;
}
div#calendar div.header span.title{
    color:#FFF;
    font-size:18px;
}
div#calendar div.header a.prev{
    left:0px;
}
div#calendar div.header a.next{
    right:0px;
}
/*******************************Calendar Content Cells*********************************/
div#calendar div.box-content{
    border:1px solid #787878 ;
    border-top:none;
}
div#calendar ul.label{
    float:left;
    margin: 0px;
    padding: 0px;
    margin-top:5px;
    margin-left: 5px;
}
div#calendar ul.label li{
    margin:0px;
    padding:0px;
    margin-right:5px;  
    float:left;
    list-style-type:none;
    width:80px;
    height:40px;
    line-height:40px;
    vertical-align:middle;
    text-align:center;
    color:#000;
    font-size: 15px;
    background-color: transparent;
}
div#calendar ul.dates{
    float:left;
    margin: 0px;
    padding: 0px;
    margin-left: 5px;
    margin-bottom: 5px;
}
/** overall width = width+padding-right**/
div#calendar ul.dates li{
    margin:0px;
    padding:0px;
    margin-right:5px;
    margin-top: 5px;
    line-height:80px;
    vertical-align:middle;
    float:left;
    list-style-type:none;
    width:80px;
    height:80px;
    font-size:25px;
    background-color: #DDD;
    color:#000;
    text-align:center; 
}
:focus{
    outline:none;
}
div.clear{
    clear:both;
}

5. Now let us show the calendar.

Create a test file "/resources/views/calendar.blade.php".

<html>
<head>   
<link rel="stylesheet" type="text/css" href="{{asset('/css/calendar.css')}}"/>
</head>
<body>
<div class="container-fluid">
<div class="media_box">
<div class="row media_box">
<div class="col-md-6">
<?=$calendar?>
</div>
</div>
</div>
</div>
</body>
</html>



Hopefully this simple tutorial helped you with your development.

If you have questions or find any mistakes in above tutorial, do leave a comment below to let us know.

Friday 11 September 2015

Social authentication in laravel 5 using laravel socialite

Hi Everybody

In this blog we will discuss about user login process form based authentication and social authentication in laravel 5.

A new package added laravel socialite to provide social authentication in laravel 5. Before laravel 5 their is only form based authentication now using Laravel Socialite it’s provides a simple, convenient way to authenticate with OAuth providers. laravel socialite currently supports 5 OAuth providers authentication in laravel 5, which are Facebook, Twitter, Google, GitHub and Bitbucket. So you can work with both type of user login process form based authentication and social authentication in laravel 5.

How to setup social authentication in laravel 5 :-

To setup socialite we need to add some packages and Facades below i am sharing steps to setup laravel socialite.


Social authentication in laravel 5

1. Include package :- First we need to include socialite package to get started with Socialite, for include the package go to your composer.json file and below code to require section :-


"laravel/socialite": "~2.0"

Example :- so now your file code of require section looks like:-

"require": {
   "laravel/framework": "5.0.*",
   "laravel/socialite": "~2.0"
},

2. Register provider and facades :- to register provider you need to add this Laravel Framework Service Providers list. for this go to config/app.php and add below code to “providers” array to further use:


'Laravel\Socialite\SocialiteServiceProvider',
Example :- so now your file code of provider array section looks like:-


'providers' => [
   /* more already here */
  'Laravel\Socialite\SocialiteServiceProvider',

Facades :- To register facades go to config/app.php and add below code to “aliases” array :


'Socialize' => 'Laravel\Socialite\Facades\Socialite',
Example :- so now your file code of aliases array section looks like:-


'aliases' => [
   /* more already here */
  'Laravel\Socialite\SocialiteServiceProvider',

3. Get package from remote :- Now after add packages we need to install Socialite package in our application for this you need to run composer update command. for this pick up your laravel application directory path in CLI or terminal and run.

composer update
After install Socialite packages successfully we need to setup oauth providers credentials, routes and controllers

4. Setup OAuth providers credentials :- Now we need to create OAuth applications on providers like facebook, google, twitter, github etc. to get client id and client secret which need to authenticate with providers.
After getting client id and secret we need to setup credentials. To setup OAuth providers credentials go to config/services.php and add your provider config to existing “return” array like below


'github' => [
    'client_id' => 'your-github-app-id',
    'client_secret' => 'your-github-app-secret',
    'redirect' => 'http://your-callback-url',
],
Note:- for all provider add configuration(client id, client secret and redirect) for others like ‘facebook’, ‘google’, ‘twitter’.

5. Routes :- Now You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. so add routes in app/Http/routes.php like :-


// Redirect to github to authenticate
Route::get('github', 'AccountController@github_redirect');
// Get back to redirect url
Route::get('account/github', 'AccountController@github');

6. Controller :- so according to routes you need to set your controller function and make social authentication with use of facades like


public function redirectToProvider() {
  return Socialize::with('github')->redirect();
}

public function handleProviderCallback() {
  $user = Socialize::with('github')->user();
}

7. Retrieve user details :- After get success authenticate you can get all user details with $user object like


$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();
Now you have successfully setup-ed social authentication in laravel 5 using laravel socialite. Below we see an example of github social authentication.

Social authentication in laravel 5 with Github :-

Now we will explore step by step an example of github login integration in laravel 5.


1. Create OAuth App :- 
A. To create an application signin in your github account.
B. Click on “settings” icon then click on “Applications” link
C. Then Click on “Register New Application” button at top right corner.
D. Now Add Application name, Homepage URL, Authorization callback URL and click on submit this will generate your Client ID and Client Secret.

2. Setup OAuth credentials :- To setup OAuth providers credentials go to config/services.php and add your provider config to existing “return” array like below


'github' => [
    'client_id' => 'f285091e4d346f1ac05459',
    'client_secret' => '866e847c2343fb77dc21a68f5cbc234fea41d7549e8c62',
    'redirect' => 'http://localhost/mylara5/account/github',
],

3. Routes :- Now you need to create routes so add routes in app/Http/routes.php.


Route::get('github', 'AccountController@github_redirect');
Route::get('account/github', 'AccountController@github');

4. Controllers :- Now you need to add authentication and redirection code with facades to get authenticate with github


<?php namespace App\Http\Controllers;
use Redirect;
use Socialize;
class AccountController extends Controller {
  // To redirect github
  public function github_redirect() {
    return Socialize::with('github')->redirect();
  }
  // to get authenticate user data
  public function github() {
    $user = Socialize::with('github')->user();
    // Do your stuff with user data.
    print_r($user);die;
  }
}

5. View :- Add a link or button to your view where you want to add github authentication link like add below link to resources/views/login.blade.php.


<a href="{!!URL::to('github')!!}">Login with Github</a>

Now click on login link it will redirect you to github. then after login redirect back to your redirect url and you will get user data, now add your stuff to user login process. So now you can easily add other providers like facebook, twitter to add social authentication in laravel 5.

Friday 4 September 2015

How to send email through terminal in ubuntu?

Send Email through Terminal:

Hi everybody,

In this blog we will cover email sending through terminal in ubuntu.
 
1. For send a email through terminal firstly install the postfix using this

sudo apt-get install postfix
  
2. Now go to this file

sudo nano /etc/postfix/main.cf

and change

myhostname = example.com

3. Put in name of your domain into myhostname.

4. If you want to have mail forwarded to other domains, replace alias_maps with virtual_alias_maps and point it to /etc/postfix/virtual.

virtual_alias_maps = hash:/etc/postfix/virtual

5. The rest of the lines are set by default. Save, exit, and reload the configuration file to put your changes into effect:

sudo /etc/init.d/postfix reload

6. Now run this for checking through terminal

sendmail sample-email@example.org

Friday 21 August 2015

Laravel 5.1: Upload a image using ajax and jquery without submit a form

Hi Everybody,

In this blog we will cover upload a image in laravel 5.1 using ajax and jquery without submitting a form.

View template
ven_pers_info.blade.php

<html>
<head>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js">
<script>
$("#uploadPhoto").on("change", function (e) {
        var file_data = $("#uploadPhoto").prop("files")[0];   // Getting the properties of file from file field
        var form_data = new FormData();                  // Creating object of FormData class
        form_data.append("file", file_data)              // Adding extra parameters to form_data
        $.ajax({
            url: '/service/upload',
            dataType: 'script',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         // Setting the data attribute of ajax with file_data
            type: 'post',
            success: function (data) {
                console.log(data);
            }
        })
    })
</script>
</script>
</head>
<body>
<div class="alert alert-danger">
{{@$errors}}
</div>
<div class="alert alert-success">
{{@$success}}
</div>
<form action="/upload/photo" method="post" name="upload" enctype="multipart/form-data" id="upload">
<input id="uploadPhoto" type="file" multiple="" style="visibility: hidden; width: 1px; height: 1px" name="uploadPhoto">
<button class="btn btn-default vido_btn" onclick="document.getElementById('uploadPhoto').click(); return false" type="submit">Upload image</button>
</form>
</body>
</html>

Routes code
route.php
<?php
Route::post('upload/photo', 'VendorPersonalController@imageUpload');


Controller code
VendorPersonalController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use URL;
use App\User;

class VendorPersonalController extends Controller
{

public function __construct()
    {
        $this->uploaddir = public_path() . '/img/profile/';

    }

public function imageUpload()
    {
         $user = new User();
         if (!Input::hasFile('file')) {
            return view('ven_pers_info',['errors' => "File not found, please try again"]);
        }
        if(!$user->uploadImg('file', $this->uploaddir)){
            return view('ven_pers_info',['errors' => "File not found, please try again"]);
        }
        return view('ven_pers_info', ['success' => "File successfully uploaded"]);
}


Model code
User.php

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use DB;
use Auth;
use Illuminate\Support\Facades\Input;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['first_name','last_name', 'mobile', 'email', 'password', 'img_url', 'user_type'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

     public function uploadImg($fileField, $dirName) {
        if (Input::hasFile($fileField)) {
            $base_url = URL::to('/');
            if (!file_exists($dirName)) {
                mkdir($dirName, 0777, true);
            }
            $time = md5(microtime());
            $extension = Input::file($fileField)->getClientOriginalExtension();
            $img_hash = $base_url . '/img/profile/' . $time .'.'. $extension;
            if (!(Input::file($fileField)->move($dirName, $img_hash))) {
               return false;
            }
            return true;
        }
    }

}

If you occure some problem please comment on this post.