Browse Category: PHP

Implement CAPTCHA In CodeIgniter

CAPTCHA is a randomly generated string (or a set of images) that appears when verification is required. It is an essential requirement for cutting down the spam at a website. In many cases, it is the only line of defense a website has against bots that spam websites.

CAPTCHA in CodeIgniter

In this tutorial, I will demonstrate how you can easily implement CAPTCHA in your CodeIgniter projects.

Create Controller

The process starts with the creation of the Controller.

Create a file named captcha.php in the Controller folder. Open the file in your code editor and add the following code to it:

Code Explanation

Here is a brief explanation of the various components of the Controller code:

Load CAPTCHA Helper

Form Submission

CAPTCHA Configuration

Refresh CAPTCHA

Create the View

The next step is the creation of the View. for this, create a folder in the View folder. Go into the folder and create another folder with the name captcha. inside this folder, create a file named index.php. Add the following code to the file:

Another Method of Calling CAPTCHA with Validation

Here is another method that is used to call in CAPTCHA through CodeIgniter helper and then validate it.

How to Integrate Pardot with WordPress via Contact Form 7

When you want to submit your form to third-party CRM like (pardot, Salesforce, MailChimp etc.) or if you want to
change action URL of the form please following steps.

To get this to work you need to have following things.

1.   WordPress website
2.  Contact Form7 Plugin – WordPress Plugin
3.  Forms: 3rd Party Integration – WordPress Plugin
4.  Pardot and the ability to create form handler


1. Create a Form using Contact Form7 which you want to submit on third-party CRM.
2. Create a Form Handler on pardot for the fields which you have used in contact form7 form.
3. Go to WordPress admin panel -> Contact -> 3rd party Services

i.  Now click on ‘[+]3rd-Party Service: Pardot‘ and give some service name.
ii. Next, you have to add 3rd party action URL into ‘Submission URL

Imp Note:  Action URL into ‘Submission URL’ must be HTTPS. This plugin does not support HTTP URL.
select the form from ‘Attach to Forms’ options

iii. Now you have to map your contact form fields with pardot form fields. Enter all contact form fields into
‘Form submission Field’ column and all pardot fields into ‘3rd-Party Field’ column.

Imp Note:  Values of ‘Form submission Field’ and ‘3rd-Party Field‘ must be identical. Small space or difference will break your submission.

iv. Next setup redirect URL into Contact Form7 settings.
v.  Now copy contact Form7 shortcode and paste it into any page.That’s it.

How to check user exist or not in pardot prospect using api-php

The Pardot API should be accessed via POST for all operations . For the most part the API does not use the standard HTTP response codes to convey the outcome of the request, rather it always returns 2 response codes and sends back its own set of status codes that need to be handled.

Steps for the check user in prospect :

Step 1 : Login to pardot by api :

$url = “https://pi.pardot.com/api/login/version/3?email=useremail@email.com&password=pardot_password&user_key=********************************”;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);

$xml = simplexml_load_string($response);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

$api_key = $array[‘api_key’];

Above API will return access token in response(api_key).

Step 2 : Check user :

$url = “https://pi.pardot.com/api/prospect/version/4/do/read/email/search_user_by_email?user_key=********************************&api_key=$api_key”

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);

 

If user exist then it will return [{“stat” : “ok”] otherwise it will return [{“stat”:”fail”}]

 

In the same way we can check user in pardot account also;

Repeat the above step for check user in account, there are only single change in second api.Replace prospect with account.

https://pi.pardot.com/api/acount/version/4/do/read/email/search_user_by_email?user_key=********************************&api_key=api_key

Top 5 PHP Frameworks of 2017

List of top 5 PHP Frameworks of 2017

Before beginning the list of top 5 PHP frameworks of 2017, PHP is one of the most favored server-side scripting languages known for its simplicity, PHP frameworks complement PHP, by providing developers with some pre-built modules, a platform to create robust, reusable components, and by enabling faster development cycles.

PHP frameworks give the users a basic structure, with some pre-built modules to develop robust web applications faster. These frameworks enforce coding standards and development guidelines hence standardizing the process and stabilizing the product.

PHP frameworks use Model View Controller(MVC) architecture, where the development of the business logic is independent of both the underlying data and the overlaying presentation view. MVC helps developers to focus on their specific areas without worrying if their code will adversely affecting the development of the other modules or not. This breaking up of the development process into independent modules increases the speed of the entire development process and improves the stability and quality of the product.

Advantages of using frameworks

  • Rapid development using the libraries and tools provided by the framework
  • Easy to upgrade and maintain the developed applications
  • Excellent community support
  • Security features such as Input filtering and Output encoding

Top 5 PHP frameworks of 2017

There are a wide variety of PHP frameworks, many of them are open source frameworks. The most popular open-source PHP frameworks are:

google trends

  1. Laravel

As far as frameworks go, Laravel takes the cake with the most number of personal and professional users. The 2015’s Sitepoint survey indicates that excellent documentation, solid features and a thriving, growing support community has made Laravel a clear winner in the space of PHP framework. Google trends on PHP frameworks show similar results.

  1. Symfony

One of the older players, Symfony is considered to be a stable base for many other newer frameworks including Laravel. The quick adaptability and widely used documentation of Symfony makes it one of the most dependable PHP frameworks.

  1. CodeIgniter

A simple, powerful PHP framework, CodeIgniter is known for its flexibility and hassle-free installation. CodeIgniter is supposed to have an easy learning curve thus making it the best choice for beginners.

  1. CakePHP

One of the oldest frameworks, CakePHP has retained its strong user base and has continued to grow. It also boasts of an impressive portfolio consisting of brands such as BMW and Express.

  1. Zend Framework

Zend is considered to be a very stable and robust framework recommended for big, enterprise-level projects. It has a wide variety of features which facilitates the development of quality applications for enterprise clients.

What is REST API in PHP?

Before explaining what is ‘REST API‘ we should know what is ‘REST’ and ‘API’.

REST stands for ‘Representational State Transfer’. REST is web standards-based architecture and uses HTTP Protocol for exchanging data between applications or systems. It is a simple way to interact with independent systems.

API stands for ‘Application Programming Interface’. Basically, these are small functions which allow two different systems to talk/interact with each other.

In many applications REST API’s are used because it’s a simple and lightest way to Create, Read, Update, Delete (CRUD) data between different applications over the internet. To develop Android, IOS mobile apps REST APIs are being used.

When you hit an API your request is being sent to the remote server, then it performs some required functions and returns its response in JSON or in XML format.

In REST API following HTTP methods are used,

GET – Use to retrieve data.
POST – It is used to add or insert data into a database.
PUT/PATCH – It is used to update any existing records.
DELETE – To delete any existing records DELETE method is used.

PHP for the Internet of Things

Analysts claim the connected devices to reach the mark of 6.5 billion by the starting of 2017. This makes PHP and IOT go hand in hand. Thanks to icicle, one can write asynchronous code using synchronous coding techniques in PHP. It means that now the PHP code is able to run several tasks by using the same script. Methods of asynchronous programming provide better data exchange between connected gadgets. Some hardware platforms such as Arduino already support PHP, and you can control Arduino board with your PHP-based script. There is also a possibility to build a PHP application that uses GPS data gathered from an IOT device. Like the GPS sensor on your Android phone can send its location to the Bluemix cloud, and the PHP application is able to publish this data on your website.

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.