Browse Category: PHP

How To Show Multiple Overlays In Google Maps

Overlays or Markers are quite important in Google Maps. Many times we come across situations when we need to show multiple overlays (markers) in our Map. In this tutorial I will be explaining how we can plot markers at desired locations using Lat Long coordinates.

In my script I have taken source and destination and have shown route with Overlays (Markers) using Lat Lng.

<html>
<head>

<title>Overlays in Google Maps using HTML & JS</title>

<style>
#map
{
width: 90%;
height: 600px;
border: 1px solid #a0a0a0;
}
</style>

</head>
<body>

<div id=”map”>
</div>

<script src=’https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true’></script>
<script src=’https://hpneo.github.io/gmaps/gmaps.js’></script>

<script>
var mapObj = new GMaps({
zoom:15,
el: ‘#map’,
lat: 19.027069,
lng: 72.838101
});

//Path is a 2D array storing source to destination coordinates
var path =[
[19.027446, 72.836856],
[19.026452, 72.836491],
[19.025295, 72.835826],
[19.024403, 72.835311],
[19.023023, 72.834731],
[19.021664, 72.833787],
[19.020812, 72.833122],
[19.019737, 72.832242],
[19.020122, 72.831620],
[19.020772, 72.830912],
[19.021056, 72.830676]
];

var pl = mapObj.drawPolyline({ //to show route

path: path,
strokeColor: ‘#76ff03’,
strokeOpacity: 1,
strokeWeight: 10
});

mapObj.drawOverlay({ // to show source marker (overlay)
lat: 19.027446,
lng: 72.836856,
content: ‘<div class=”overlay”><img src=”http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/map-marker-icon.png” style=”height:30px;width:30px;” /></div>’
});

mapObj.drawOverlay({ // to show destination marker (overlay)
lat: 19.021056,
lng: 72.830676,
content: ‘<div class=”overlay”><img src=”http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/map-marker-icon.png” style=”height:30px;width:30px;” /></div>’

});

</script>
</body>
</html>

We have created Map object and added it’s properties. We are using two functions drawPolyline to show the route and drawOverlay to plot marker. If  you wish you can change the Source and Destination marker image by changing the image URL in drawOverlay function.

You can run this script by copying the code and saving it with a meaningful name with .html extension. After running it on your browser it will look like this.

map1

Since my source and destination were near so I didn’t use Database to store coordinates. I have used simple static array, if you have multiple coordinates then you need to fetch them from database and store them in array.

I hope the code is self explanatory 🙂 If you still find it difficult to understand please drop a comment I will be more than happy to answer it.

Make future payment using Braintree payment gateway

This tutorial is for those who are developing a mobile application and they want to charge a customer(one or more time) in future. In this tutorial I am going to explain backend functionality in details.

Most of the time we need charge to  customer  in future. Some developers may store details in the database but this is not the best way when it comes to security. Fortunately this feature is provided by braintree and stripe payment gateways. Following tutorial will explain you how we can use braintree API.

Before we start a tutorial make sure that you have a braintree(Sandbox/Production) account, if you don’t have an account  you can open your braintree sandbox account from here Sandbox Account. Mobile developers need to install braintree provided sdk from here Mobile SDK
Braintree payment screen

Once you installed SDK successfully you can see the above screen and fields like card Number, Expiration Date and CVV Number which is provided by braintree you don’t need to do any code for that.

If you using sandbox account enter following Card details for testing purpose.

Sandbox Card Number: 4242 4242 4242 4242

Card Exp: Any future expiry month/Year

CVV: 123

When user click “Buy Now” button braintree SDK returns you paymentMethodNonce .  What you’ll do next step. Simply you’ll send paymentMethodNonce to your server through webservice.

Now the actual backend functionality start here.

Suppose you are sending the parameter paymentMethodNonce to the API YourServer.com/add_card_token.php

In add_card_token.php i will use the method provided by braintree (make sure you have downloaded PHP braintree library if not then click here)

<?php

require_once ‘lib/Braintree.php’; //installed braintree php library and include over here

Braintree_Configuration::environment(‘sandbox’);

Braintree_Configuration::merchantId(‘your_account_merchant_id’);

Braintree_Configuration::publicKey(‘public_key’);

Braintree_Configuration::privateKey(‘private_key’);

$paymentMethodNonce = $_POST[‘paymentMethodNonce ‘];//Getting parameters from mobile dev

$result = Braintree_Customer::create( array( ‘firstName’ => ‘abc’, ‘lastName’ => ‘efg’, ‘company’ => ‘Nanostuffs’, ‘paymentMethodNonce’ => $paymentMethodNonce ));

$customerid = $result->customer->id; //Store this info into the database

$card_token = $result->customer->paymentMethods[0]->token;//Store this info into the database

?>

The method (Braintree_Customer::create) will returns you all the basic information about the card like expiry, last four…

You will get customer id $result->customer->id and card_token in response $result->customer->paymentMethods[0]->token

You will store this information into the database for that particular customer.

Great, now you are ready to charge a customer in future anytime. Suppose i want to charge that customer now i will use the following method.

<?php

require_once ‘lib/Braintree.php’; //installed braintree php library and include over here

Braintree_Configuration::environment(‘sandbox’);

Braintree_Configuration::merchantId(‘your_account_merchant_id’);

Braintree_Configuration::publicKey(‘public_key’);

Braintree_Configuration::privateKey(‘private_key’);

try{

$result = Braintree_Transaction::sale(array(  ‘amount’ => ‘100’,

‘paymentMethodToken’ => $customer_id,

‘options’ => [ ‘submitForSettlement’ => True  ] )

);

if($result->success) {

$transactionId = $result->transaction->id;

}else{

$err = ”;

foreach($result->errors->deepAll() AS $error) { $err.= $error->message.” “; }

echo $err;

}

}catch(Exception $e)

{}

?>

Check and parse proper response returned by braintree. You have charged to the customer successfully. If you run the same method again you can see the charge successfully. Without entering user card details again.

You can achieve this using any sever side langauge. I am familiar with PHP only.

Let us know if this tutorial really help you 🙂

Adding Ion Auth authentication library in a Codeigniter Framework

Ion Auth is a simple and lightweight authentication library for the CodeIgniter framework.

Installation

  1. Download the latest version: http://github.com/benedmunds/CodeIgniter-Ion-Auth/zipball/2
  2. Copy the files from this package to the correspoding folder in your application folder. For example, copy Ion_auth/config/ion_auth.php to system/application/config/ion_auth.php.
  3. You can also copy the entire directory structure into your third_party/ folder. For example, copy everything to /application/third_party/ion_auth/
  4. Run the appropriate SQL file from the /sql directory.
  5. You load Ion Auth just link any other library: $this->load->library(“ion_auth”); from your controller.You can also autoload the library from autoload.php:$autoload[‘libraries’] = array(‘database’,’ion_auth’);
  6. You can also autoload the library from autoload.php :$autoload[‘libraries’] = array(‘database’,’ion_auth’);

The default login is:

  • Email: admin@admin.com
  • Password: password

Class Function In Ion Auth

1. login()

Logs the user into the system.

Parameters

  1. ‘Identity’ – string REQUIRED. Username, email or any unique value in your users table, depending on your configuration.
  2. ‘Password’ – string REQUIRED.
  3. ‘Remember’ – boolean OPTIONAL.

2. logout()

Logs the user out of the system.

3. register()

Create a new user.

Parameters

  1. ‘Identity’ – string REQUIRED. This must be the value that uniquely identifies the user when he is registered. If you chose “email” as $config[‘identity’] in the configuration file, you must put the email of the new user.
  2. ‘Password’ – string REQUIRED.
  3. ‘Email’ – string REQUIRED.
  4. ‘Additional Data’ – multidimensional array OPTIONAL.
  5. ‘Group’ – array OPTIONAL. If not passed the default group name set in the config will be used.

4. update()

Update a user.

Parameters

  1. ‘Id’ – integer REQUIRED.
  2. ‘Data’ – multidimensional array REQUIRED.

5. delete_user()

Delete a user.

Parameters

  1. ‘Id’ – integer REQUIRED.

7.forgotten_password()

Resets a users password by emailing the user a reset code.

Parameters

  1. ‘Identity’ – string REQUIRED. (as defined in config/ion_auth.php)

8. forgotten_password_complete()

Final step of resetting a users password. The user comes to this page from their email.

Parameters

  1. ‘Code’ – string REQUIRED.

9. logged_in()

Check to see if a user is logged in.

10. is_admin()

Check to see if the currently logged in user is an admin.

Parameters

  1. ‘id’ – integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used.

11. in_group()

Check to see if the currently logged in user is in the passed in group.

Parameters

  1. ‘Group ID or Name’ – string, integer or array of strings and integers REQUIRED.
  2. ‘User ID’ – integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used.

12. username_check()

Check to see if the username is already registered.

Parameters

  1. ‘Username’ – string REQUIRED.

13. email_check()

Check to see if the email is already registered.

Parameters

  1. ‘Email’ – string REQUIRED.

14. identity_check()

Check to see if the identity is already registered.

Parameters

  1. ‘Identity’ – string REQUIRED.

15. is_max_login_attempts_exceeded()

If login attempt tracking is enabled, checks to see if the number of failed login attempts for this identity or ip address has been exceeded. The controller must call this method and take any necessary actions. Login attempt limits are not enforced in the library.

Parameters

  1. ‘Identity’ – string REQUIRED.

16 User()

Get a user.

Parameters

  1. ‘Id’ – integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used.

17. users()

Get the users.

Parameters

  1. ‘Group IDs’ – array OPTIONAL. If an array of group ids are passed (or a single group id) this will return the users in those groups.

18. group()

Get a group.

Parameters

  1. ‘Id’ – integer REQUIRED.

19. groups()

Get the groups.

20. messages()

Get messages.

21. get_users_groups()

Get all groups a user is part of.

Parameters

  1. ‘Id’ – integer OPTIONAL. If a user id is not passed the id of the currently logged in user will be used.

22. add_to_group()

Add user to group

Parameters

  1. ‘Group_id’ – integer or array REQUIRED.
  2. ‘User_id’ – integer REQUIRED.

23. remove_from_group()

Remove user from group(s)

Parameters

  1. ‘Group_id’ – NULL, integer or array REQUIRED. NULL will remove the user from all groups.
  2. ‘User_id’ – integer REQUIRED.

24. create_group()

Create a group

Parameters

  1. ‘group_name’ – string REQUIRED.
  2. ‘group_description’ – string.

25. update_group()

Update details of a group

Parameters

  1. ‘group_id’ – int REQUIRED.
  2. ‘group_name’ – string REQUIRED.
  3. ‘group_description’ – string.

26. delete_group()

Remove a group. Removes the group details from the configured ‘groups’ table. Users belonging to the group are stripped of this status (references to this group are removed from users_groups), but user data itself remains untouched.

Parameters

  1. ‘group_id’ – int REQUIRED.

28. errors()

Get the errors.

29. set_hook()

Set a single or multiple functions to be called when trigged by trigger_events(). See an example here: http://gist.github.com/657de89b26decda2b2fa

Parameters

  1. ‘Event’ – string REQUIRED.
  2. ‘Name’ – string REQUIRED.
  3. ‘Class’ – string REQUIRED.
  4. ‘Method’ – string REQUIRED.
  5. ‘Arguments’ – Array OPTIONAL.

30. trigger_events()

Call Additional functions to run that were registered with set_hook().

Parameters

  1. ‘Name’ – String or Array REQUIRED.

 

 

Error with memcached in wordpress on windows localhost.

I was trying to setup my wordpress website, www.nanostuffs.com, on windows localhost & had really tough time solving memcache related issues. After 2 days of efforts, finally here is perfect solution:

1. Verify your PHP version matches the one which was for your live site. In my case, it was 5.3.x on live site but had 5.6 on my latest xampp local server. So I installed installed earlier version of xampp that supported PHP 5.3.x

 

2. Install memcache on Windows:

– Follow these steps properlyh http://stackoverflow.com/questions/3016656/how-to-enable-memcace-in-wamp

– Note the php_memcached.dll should match your PHP version, so download the right one from here https://pecl.php.net/package/memcache/3.0.8/windows

– The .exe files that you’ll run from above link (even command prompt) run them as administrator.

– To confirm you did all of it correctly, open Task Manager -> Services -> memcached Server should be running.

 

3. In WAMP or XAMPP, copy the php_memcached.dll file to C:xamppphpext folder if you havent done already.

4. Open php.ini & add extension=php_memcached.dll

5. Stop & restart WAMP or XAMPP, it should start properly without any error shown for memcache. In Wamp, verify the extention is coming without any exclamation mark.

 

6. MOST Important Step:

– Open your wp-config.php file

– Search for $memcached_servers & if it mentions like this:

$memcached_servers=array ( ‘default’ =>  array ( 0 => ‘unix:///tmp/memcached.sock’, ), );

Make it

$memcached_servers=array ( ‘default’ =>  array ( 0 => ‘127.0.0.1:11211’, ), );

 

7. Run your WordPress site & it should not show the memcache error now.

 

Hope this helped saved your time & frustration.

How to use PDO database connection in PHP

<?php
$string = ‘Test’; # user submitted data
try {
#connection
$conn = new PDO(‘mysql:host=localhost;dbname=myDB’, $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$data = $conn->query(‘SELECT * FROM myTable WHERE name = ‘ . $conn->quote($string)); // $conn->quote used to protect SQL injection
foreach($data as $rows) {
print_r($rows);
}
} catch(PDOException $e) {
echo ‘ERROR: ‘ . $e->getMessage();
}
?>

How to create select box with searching support using jQuery

<html>
<head>
<title>How to create HTML select box with searching support using jQuery</title>
<link href=”select2.css” rel=”stylesheet”/>
<script src=”http://code.jquery.com/jquery-1.8.0.min.js”></script>
<script src=”select2-2.js”></script>
<script>
$(document).ready(function() {
$(“#states”).select2();
});
</script>
</head>
<body>
<select style=”width:300px” id=”states”>
<optgroup label=”Alaskan/Hawaiian Time Zone”>
<option value=”AK”>Alaska</option>
<option value=”HI”>Hawaii</option>
</optgroup>
<optgroup label=”Pacific Time Zone”>
<option value=”CA”>California</option>
<option value=”NV”>Nevada</option>
<option value=”OR”>Oregon</option>
<option value=”WA”>Washington</option>
</optgroup>
<optgroup label=”Mountain Time Zone”>
<option value=”AZ”>Arizona</option>
<option value=”CO”>Colorado</option>
<option value=”ID”>Idaho</option>
<option value=”MT”>Montana</option><option value=”NE”>Nebraska</option>
<option value=”NM”>New Mexico</option>
<option value=”ND”>North Dakota</option>
<option value=”UT”>Utah</option>
<option value=”WY”>Wyoming</option>
</optgroup>
<optgroup label=”Central Time Zone”>
<option value=”AL”>Alabama</option>
<option value=”AR”>Arkansas</option>
<option value=”SD”>South Dakota</option>
<option value=”TX”>Texas</option>
<option value=”TN”>Tennessee</option>
<option value=”WI”>Wisconsin</option>
</optgroup>
<optgroup label=”Eastern Time Zone”>
<option value=”CT”>Connecticut</option>
<option value=”MI”>Michigan</option>
<option value=”PA”>Pennsylvania</option>

<option value=”RI”>Rhode Island</option>

<option value=”SC”>South Carolina</option>
<option value=”VT”>Vermont</option>
<option value=”VA”>Virginia</option>
<option value=”WV”>West Virginia</option>
</optgroup>
</select>
</body>
</html>

Note:

Download select2.js, select2.css  files from below location

https://github.com/ivaynberg/select2/blob/master/select2.js

https://github.com/ivaynberg/select2/blob/master/select2.css

Laravel introduction

What is Laravel ?

Laravel is a free, open source PHP web application framework, designed for the development of model–view–controller (MVC) web applications. Laravel is released under the MIT license, with its source code hosted on GitHub.

Tutorial Details
Name : Laravel – PHP Framework
Type : PHP Framewrok
Language : PHP
Level : Beginner
Estimated Time : 40 Minuets
Comments : Next generation PHP Framework

Hello,
Today I am going to introduce a new PHP Framework called Laravel. It’s a young PHP framework. Before starting this tuts, lets go to know why you have to learn framework?

Yes, definitely, there is so much PHP framework (like zend, cake, codeigintor, yii etc.) available. But why need new framework? There are some difference between conventional framework and LARAVEL.

WHY YOU LEARN?
1. Very Light framework
2. Powerful and Flexible
3. Elegance and Simplicity
4. Programming (i.e. framework) doesn’t have painful
5. Well decorated Documents.
6. No need to configure
7. CURD & PHP template system support
8. Migration System
9. and more…

History and Author:
It’s developed in April 2011 by Taylor Otwell. He is Software Engineer at UserScape, where he works on the next generation of HelpSpot. Previously, he developed Microsoft .NET solutions for one of the largest freight carriers in the nation.

Well, if some interest has grown in your mind to know more about the LARAVEL, then let’s go to know more about this.

Requirements:
1. Localhost (WAMP/XAMPP/MAMP etc.)
2. PHP 5.3
3. MySql

Let’s go to start our Journey…
1. Go to Laravel website [www.laravel.com]
2. Click download and download the latest version of laravel

3. Extract this zip into your web root. Currently I am using XAMPP in windows. For xampp, go to xampp/htdocs/ and I have created a new folder called ‘laravel‘. After then, I copied all the file and folder from extracted zip and paste into laravel folder. So, my directory is now like this- http://localhost/laravel/

4. Now, go to browser and type your laravel directory to access. Our url should be http://localhost/laravel and finally type the public folder after that. The url like http://localhost/laravel/public/. Oky, now you are seeing your first laravel application home page.

 

 

 

 

 

 

 

 

 

 

 

 

 

5. Our application is almost done. To ensure more security, then we have to set the application key. For this, go to your laravel directory and find the applicaiton/config/application.php. Open this file and find the ‘key’ => ‘YourSecretKeyGoesHere!‘ line. Its a 32 hashing security key. You can generate any random key by yourself.

 

 

 

 

 

 

 

 

 

 

 

 

 

6. Now browse your application laravel and you may seeing some error in your apps. OK, its a common problem for all, Now, clear your browser history and cookies. After doing this, browse again. I think, it’s working properly now.

7. Some other configuration can be, but I think it is no needed for now. So, save this file.

 

Now 1 thing is left. Database configuration. Lets, go to for this-

1. Go to your laravel directory and open this file ‘application/config/database.php’ for database configuration.

2. After open this file, find out the ‘default’ => ‘mysql’, I am going to use mysql database so that I am keeping this data.

3.
Now find out the below link for database configuration.

‘mysql’ => array(
‘driver’   => ‘mysql’,
‘host’     => ‘localhost’,
‘database’ => ‘database’,
‘username’ => ‘root’,
‘password’ => ”,
‘charset’  => ‘utf8′,
‘prefix’   => ”,
),

And then set your host name. Create a database entitled ‘laravel‘ by using browser. Then put the database name and save the file.

Oky, now you have completed your first laravel configuration into your localhost. That’s the best way to configure laravel framework into your server.

How to create form in Laravel

Form is a most expected elements in website as well as web based application. Each and every interactive web apps must have a form option to communicate between users and administrator. Whatever you want to write in website, there is not alternative about form. It could be in chat, message, as well as comments.

In laravel 4, you have huge flexibility to create HTML form easily. Today I will gonna to show you how to create a simple form in laravel. Let’s open route.php file to change our routing.

Route::get('/createform', function()
{
return View::make('createform');
});

Just change the view file name and write new file name that is ‘createform’. Save and close this file. Open apps/views directory and create a new file. File name should createform.blade.php that we defined in route.php file.

<?php

{{ Form::open() }}

{{ Form::label(‘name’, ‘Full Name: ‘) }}

{{ Form::text(‘name’) }}

{{ Form::label(‘email’, ‘Email Address: ‘) }}

{{ Form::email(‘email’) }}

{{ Form::label(‘password’, ‘Password: ‘) }}

{{ Form::password(‘password’) }}

{{ Form::submit(‘Save Data’) }}

{{ Form::close() }}

Now save your file and browse your site (http://localhost/createform). Hope you will get very simple form that will take name, email and password. Its not fancy but still work.

 

But one problem here still, if you want to submit this form, it goes to you current controller, isn’t it? You can fix this issue by 2 ways. Either by routing or controller. Let’s check two methods. Change something in createform.blade.php as follows-

by routing

{{ Form::open(array('route' => 'createform.NameOfYourMethod')) }}
by Controller

{{ Form::open(array('action' => 'YourControllerName@NameOfControllerMethodWhereYouRedirectIt')) }}

Now save it and run your page again. Hope, if you submit your page, its redirect to your desired method properly.

Remove index.php from codeigniter framework

Hi all,
Today I am going to show you, how to remove the index.php part from your codeigniter URL. There are many ways to do it, but based on my previous experience, I got it is the best way to do so. To do so, create a .htaccess file in your directory and copy the following code in your created file.

 

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

 

Now, save this file and run your codeigniter apps. Hopefully, it will work perfectly.

Thanks for reading.

How to install laravel on windows wamp server

Following are the steps to install laravel on windows local wampserver

Steps

Before installing laravel please check following services are on or not ?

a.Enable openssl

b.Click on wamp icon->Apache->Apache Modules and enable ssl_module

c.check php_sockets is enable wamp icon->PHP->Extension->php_socket

Restart all services.

1.For installing laravel on windows PHP >= 5.4  required.

2.Download Laravel from: https://github.com/laravel/laravel/archive/master.zip.

3.Extract Laravel into the www folder for WAMP.

4.Download Composer from: https://getcomposer.org/Composer-Setup.exe

5.Install Composer into the same directory where the php.exe is located.e.g my php.exe is located at wampbinphpphp5.5.12

6.Open command prompt

7.Change into the directory where you extracted Laravel e.g: cd C:wampwwwlaravel

8.Type the command: composer install.

9.Copy and paste all public folder files into WAMP’s www folder.

10.Open index.php in laravel directory edit both lines to include the installation .Directory .e.g: ‘/../bootstrap/autoload.php’ to ‘/laravel/bootstrap/autoload.php’.

11.Open bootstrappaths.php and edit the line ‘public’ => __DIR__.’/../public’, to ‘public’ => __DIR__.’/../..’

12.Open your browser and run URL : localhost/laravel/public, you will be see below output.(You have arrived on the screen)