How get an address from latitude and longitude by using google api

php

Posted on 06 Aug 15 by Vickey
  734

By using google api we can get latitude and longitude of a given location and we can also get the location details if we have latitude and longitude of that location.

With the help of below code you can get location details if you have latitude and longitude of a location

echo getAddressByLatLong('-4734774834','005347587');

public function getAddressByLatLong($loc_latitude='',loc_longitude='')
{
    $loc_latitude=trim($loc_latitude);
    $loc_longitude=trim($loc_longitude);
    $api_url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$loc_latitude.','.$loc_longitude.'&sensor=false';
    
    $location_record = @file_get_contents($api_url);
    $location_data=json_decode($location_record);

    $location_status = $location_data->status;
    if($location_status=="OK")
        return $location_data->results[0]->formatted_address;
    else
        return false;
}

 

Change the default template engine in yii2

Yii

Posted on 03 Aug 15 by Vickey
  1482

Yii use php as the template engine by default but we can change different template engine for example we can use smarty, twig and others
In this post I will use smarty as the template engine with yii. I am using yii2 and i am working on Ubuntu operating System with xampp. so lets start

1. Go to Yii root directory and you will see a file here name as 'composer.json', open this and search the like given below

  "require": {
  
        "php": ">=5.4.0",
        some code here
        some code here
        some code here
        some code here
        
        
    },

now add the below code
      

  "yiisoft/yii2-smarty": "*"


you should see something like this
    

      "require": {
  
        "php": ">=5.4.0",
        some code here,
        some code here,
        some code here,
        some code here,
        
        "yiisoft/yii2-smarty": "*"
        
    },

now go to directory name as  'config' and open web.php file and search text 'components'   and add the below code
    

    'components' => [
    
    
    
            'view' => [
                'renderers' => [
                        'tpl' => [
                        'class' => 'yii\smarty\ViewRenderer',
                    ],
                ],
            ],


 Now open you terminal and locate in yii root folder
                   

cd /opt/lampp/htdocs/yiiroot

 and update composer

sudo /opt/lampp/bin/php /usr/local/bin/composer update

( in window you need different command   'composer update')
            
after installation complete go to your controller and change your render view name
            
 return $this->render('index.tpl');

 now in your views create a file index.tpl and put your smarty code here and open your webpage you see your new tpl file content
            
            
            
            
            
            
            
            
    
    

How to write ajax responce in window popup

Js

Posted on 15 Jul 15 by Vickey
  595

We have many popup plugins and library for open a popup up with the dynamic content. but we can use widnow popup also, which is browser property. we can open our ajax responce in window popup

function openPopup(){

    $.ajax({
    
        type: "POST",
        url: "url here",
        success: function(response){
	  var win=window.open('about:blank','popup','width=600,height=200')
	  with(win.document)
	  {
	    open();
	    write(response);
	    close();
	  }
        }
    });
}

 

What is function overriding vs overloading in php oops

Object Oriented Programming

Posted on 20 Jun 15 by Vickey
  2824

Function Overriding

In the sence of Overriding is to replace parent property in child.In Overriding if we have defined a function in base class and we want to change the
its basic functionality in child class then we can do this and this is called function Overriding for example

class BaseController {
{
    public function dbConnection(){

        $host = "localhost";
        $username = "root";
        $password = "root";
        $connection = new mysqli($host, $username, $password);

    }
}



class UsersController extends BaseController {

    public function dbConnection(){

        $host = "192.168.2.00";
        $username = "root";
        $password = "PASSWORD123";
        $connection = new mysqli($host, $username, $password);

    }
}

as you cann see in base class i have a method dbConnection with code for make database connection but in child class
i have change the host and password for database connection

Function Overloading

In programming the function Overloading means is create two function with same name with different functionality by passing different arguments.
but in php we can not create two function with the same name so if we want to implement overloading in php we can take help of _call function
Here is a simple example of function overloading by using of _call function

class Calculate{

    public function __call($name, $arguments){

        if($name='sum'){

            if(count($arguments) === 2 ){
                return $this->sum1($arguments[0],$arguments[1]);
            }
            if(count($arguments) === 3){
                return $this->sum2($arguments[0], $arguments[1],$arguments[2]);
            }
        }
    }
    public function sum1($a,$b){
        echo $a+$b;
    }

    public function sum2($a,$b,$c){
        echo $a+$b+$c;
    }

}
$obj=new Calculate();
echo $obj->sum(1,2);
echo "
";
echo $obj->sum(1,2,3);

here _call magic function manage the overloading by calling different function on basis of number of arguments

Constructor and Destructor in php

Object Oriented Programming

Posted on 20 Jun 15 by Vickey
  683

Constructor

PHP5 allows us to declare constructor function.A constructor function automaticallly called when an object created.so we use it for any basic functionality which we need to use in the initialization of application for example database connectivity or setting of UI.

Class BaseConnection
{

 public function __construct() {

    $host = "localhost";
    $username = "root";
    $password = "root";
    $connection = new mysqli($host, $username, $password);
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    } 
    echo "Connected successfully";
  }
  
}
$obj=new BaseConnection(); //create object

if we are using inheritance and the base class and child class both have constructors then the paraent's class constructor will not call automatically so for run paraent constructor we need to use " parent::__construct()"

Class Connection extends BaseConnection
{
    public function __construct() {
        parent::__construct();
    }
}
$obj=new Connection(); //create object

Destructor

The Destructor function caled automatically when object destroy so if we want to destroy any variable or other member of a class then we destroy it in __destruct function
for example after complete all database operation we want to cloase database connection

Class BaseConnection
{
    public function __destruct() {
    
    $connection=mysqli_connect("localhost","user","password","db");
    mysqli_close($connection);
      
   }
}

For call parent  __destruct we use parent::__destruct() same as for __construct

Class Connection extends BaseConnection
{
    public function __destruct() {
        parent::__destruct();
    }
}

 

What is use of _get and _set methods in php

Object Oriented Programming

Posted on 18 Jun 15 by Vickey
  1127

_get method

_get method called when object try to read an inaccessible or unavailable property. This make a property that is not available.
For example in the class 'User' i have getdetails function in which i have defined 'name' 'email' and 'phone' but not defined 'dob'
so when i create an object and try to access dob then it will show a message that i gave in _get function for this property

class User{

  public function __construct() {
    $this->getdetails();
  }
  public function getdetails() {
    $this->name='vickey';
    $this->email='test@gmail.com';
    $this->phone='123456';
    return $this;
  }


  public function __get($field) {
      return $field.' field not exist';
  }
}
$tux = new User();
echo $tux->name; echo "
";
echo $tux->email; echo "
";
echo $tux->phone; echo "
";
echo $tux->dob; echo "
";

 

_set method

In set method we can set a new value for example in the below code i have email but i have set it by _set method

class User{

  public function __construct() {
    $this->getdetails();
  }
  public function getdetails() {
    $this->name='vickey';
    $this->email='test@gmail.com';
    $this->phone='123456';
    return $this;
  }


  public function __get($field) {
      return $field.' field not exist';
  }

  public function __set($field, $value) {

    if($field == 'email') {
      $this->email = 'We can not show you email';
    }
  }
}
$tux = new User();
echo $tux->name; echo "
";
echo $tux->email; echo "
";
echo $tux->phone; echo "
";
echo $tux->dob; echo "
";

 

How to extract a zip file using php

php

Posted on 18 Jun 15 by Vickey
  437

By using the below code we can extract or unzip a zip file in php

$path_of_zip='testfile.zip';
$unzip = new ZipArchive;
$unzip->open($path_of_zip);
if($unzip->open($path_of_zip))
{
     $unzip->extractTo('/path/extract');
}
$unzip->close();

 

Put your date of birth and calculate age in php

php

Posted on 18 Jun 15 by Vickey
  686

Here i am creating a function for create age.For get age we need to put date of birth in YY-mm-dd form

 

function calculateAge($date)
{

    $y = date('Y');
    $m = date('n');
    $d = date('j');
    list($yr,$mo,$day) = explode('-',$date);
    
    $now = ($y*10000+$m*100+$d);
    $past = ($yr*10000+$mo*100+$day);
    $diff = ($past-$now);
    if ($diff>0) { $age = 0 ; }
    else
    {
    $age = (($y-$yr)-1);
    if (($m>$mo) || (($m>=$mo) && ($d>=$day))) { $age++; }
    }
    return $age; 

}

and now call this function

echo calculateAge('1988-10-21');

 

File upload with image validation in laravel

Laravel

Posted on 03 Jun 15 by Vickey
  5922

Laravel provide very easy method to upload a file.So lets create a simple file upload system

Step 1: Create a action in your controller for upload a file (if you did not created it)

public function uploadImage(){

    $this->layout->content = View::make('users.uploadImage');
}

Step 2: Create a uploadImage.blade.php file /view/users/ directory and put the below code

@if($errors->any())
    {{ implode ('', $errors->all('<p><strong>:message</strong></p>'))}}
@endif
{{ Form::open(array('url'=>'/postupload','files' => true))}} 
<table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <th>Photo</th>
            <th> {{ Form::file('photo') }} </th>
        </tr>
        <tr>
            <th></th>
            <th>{{ Form::submit('Submit!',array('class' => 'btn')) }}</th>
        </tr>
</table>
{{ Form::close() }}

Now you form ready now need to create an action for post this form and upload file

Step 3: Create a action in your controller

public function postupload(){

    $userdata = array('image' => Input::get('photo'),);
     $rules = array('image' => 'image');  // validate file type image

     $validator = Validator::make($userdata, $rules);
     if($validator->fails())
    { 
        return Redirect::back()->withInput()->withErrors($validator);
    }
    else{

        $file = Input::file('photo');
        $destinationPath = 'uploads'; // give path of directory where you want to save your files
        $filename = Str::random(20) . '.' . Input::file('photo')->guessExtension();
        $upload_success = Input::file('photo')->move($destinationPath, $filename);
        return Redirect::to('success_page');
    }
}

for validation you can use this also

$rules['image'] = 'mimes:jpg,png,gif,svg,jpeg';

Step 4: Now open your routes.php file and add routes for these two action

Route::get('/uploadImage', 'UserController@uploadImage');

Route::post('/postupload', 'UserController@postupload');

Now you can upload your file

How to hide page numbers from laravel pagination

Laravel

Posted on 03 Jun 15 by Vickey
  1170

If you have large datasheet and you are showing pagination for these record on your page then it require more space to show pagination with page numbers.

Genearlly we use the below code

$publishedBlogs = Blogs::where('status', '=', 1)->simplePaginate(15);

it will show all pages numbers with previous and next link but for save our webpage space we can show only previous and next links

$publishedBlogs = Blogs::where('votes', '=', 1)->simplePaginate(15);

and for show page links on view we can use

<?php echo $users->render(); ?>
www.000webhost.com