My Programming Tutorials https://www.myprogrammingtutorials.com Lets Turn Into Professional Developer Tue, 06 Nov 2018 07:26:45 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 https://i0.wp.com/www.myprogrammingtutorials.com/wp-content/uploads/2017/01/cropped-logo.png?fit=32%2C32&ssl=1 My Programming Tutorials https://www.myprogrammingtutorials.com 32 32 3073289 Dictionaries should be free https://www.myprogrammingtutorials.com/dictionaries-should-be-free.html https://www.myprogrammingtutorials.com/dictionaries-should-be-free.html#comments Thu, 11 Oct 2018 14:56:22 +0000 https://www.myprogrammingtutorials.com/?p=643 In the current society, education is really important and the tendency starts to show up that people are trying to get the best education quality that they can. However, in most of the countries it is impossible to get an education for free. That means that if you want to become successful in the today’s… Read More »

The post Dictionaries should be free appeared first on My Programming Tutorials.

]]>
In the current society, education is really important and the tendency starts to show up that people are trying to get the best education quality that they can. However, in most of the countries it is impossible to get an education for free. That means that if you want to become successful in the today’s society, you will have to start paying money all the way from the first years of getting out of the kinder garden.

The thing which has also become popular among those studying at schools and colleges is learning of the foreign languages. That is a thing which is told to help you a lot in the future if you will have an ability to visit a place abroad. However, people say that even if you will not have that opportunity given to you, you will still be able to learn a lot by studying the second or third foreign language. The main argument is the fact that you will be learning about a new culture, while learning the language. You will find out about the new countries and their cultures when learning some words that do not happen to be real in your home country.

So, how does all of this apply to the topic of the text. Well, we can call many various ways of studying the languages, but one of the oldest and yet the best ways that you will find nowadays is the dictionary method. It has been proven that the method where you learn the new words is not that good for those who are just starting to learn the new language. Yet with the learning of the groups of words, and also the single ones later on in the process of studying, you can easily become pretty fluent in the language you are studying. The other great thing about the dictionary method is the fact that if you add it to the other methods, it will make the learning process way easier. Therefore, such an old and not really efficient method can still exist in the current learning variety.

So, why dictionaries should be free in the current society. Well, that is pretty simple. They are the only way which can be used by poor to learn the new languages. Yet, with the price of some advanced dictionaries, the poorer people are left without a chance to learn something a little over the basics. And many services are already trying to provide help with such works. For example, some volunteer programs are giving out dictionaries to the poor and those in need. For students many various programs exist, which help with their languages. For those looking for a job it is a little harder, as they have no time to actually learn something, because of their look for a job. Therefore, such people should try to use the cover letter writing service in order to save their time and do the stuff they actually need, while they can still study the foreign language a little later.

The other great reason for starting a free distribution of dictionaries is the fact that many foreign tourists come into the new countries with them, and they definitely require some help from the locals at most of their period of staying abroad. And the problem is that many of them do not know the local language or at least English, or the locals might not know how to communicate with the strangers. Moreover, many travellers travel around the world with literally no money, meaning that they would not be able to even get the simplest help from the locals. That brings us to the point where we can say that dictionaries are going to be useful for those travelling on a low budget. It will definitely help the tourists to stay informed in the foreign country and have some help from the people who they are going to be surrounded by. Also, that will help a lot with the getting of new friends. Even if you can communicate well with your friends from abroad, using one of the words from their language will definitely boost the morale of the group, and that will help to keep the nice relations between the friends.

The topic of friendship is actually a great reason to make dictionaries free. People, especially the new generations are going to be able to talk to the people from abroad, which is always good for both of those talking, as they are going to learn a lot of new stuff about each other cultures, and at the same time they will be able to communicate on any of the topics of the interests that both people share. Therefore, we can say that by giving out the free knowledge in general, we can easily create new ties with people all around the world. The other reason is the fact that the companies that print can easily make a portion of dictionaries to be given out for free. They will not lose that much money to care about it. Moreover, they can create a new version of a dictionary to be less advanced, and at the same time with the soft cover, which will decrease the price of producing of such a book way lower, and that will definitely boost the PR of that company and rating in the eyes of people.

To sum everything up, we can say that there is no doubt that dictionaries should be made free, and that will not bring anything bad to any of the sides. However, the modern companies are so scared to lose the money that they would never risk making such a PR move, because it requires some money invested into something which might not bring too many people in. Yet, we all know that free dictionaries will give many people a chance to know much more.

The post Dictionaries should be free appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/dictionaries-should-be-free.html/feed 1 643
Web Notifications Using Laravel and Pusher https://www.myprogrammingtutorials.com/web-notifications-laravel-pusher.html https://www.myprogrammingtutorials.com/web-notifications-laravel-pusher.html#comments Tue, 09 Oct 2018 10:39:48 +0000 https://www.myprogrammingtutorials.com/?p=629 Web notification is a particular message that generates from a website, whenever any update or important message is shared on the app. These messages pop up on your desktop or device even when the respective page is not opened on your current browser. These push notifications are a great addition to the traditional email and… Read More »

The post Web Notifications Using Laravel and Pusher appeared first on My Programming Tutorials.

]]>
Web notification is a particular message that generates from a website, whenever any update or important message is shared on the app. These messages pop up on your desktop or device even when the respective page is not opened on your current browser.

These push notifications are a great addition to the traditional email and marketing campaigns. As a user is notified with a push notification every time whenever any update is generated and the users just have to click on that to be notified about any update.

Pusher

Pusher is a hosted service that allows web and mobile applications to add real time data to its live functionality. It works as a real time correspondent between the servers and clients. It establishes persistent connections with the clients on HTTP using WebSocket, therefore, whenever your server receives new data, it gets instantly passed on to the respective clients for maintaining live data concurrency.

In order to integrate in all major languages and frameworks, Pusher offers several libraries to achieve the integration, including libraries of PHP, Ruby, Python, Java, .NET, Go and Node for the server, and JavaScript, Objective-C (iOS) and Java (Android) for the client.

Being known as a highly scalable real time solution for apps, Pusher first came to prominence in 2010 and since then it has continued to remain as the top choice for many. The list of its happy customers includes GitHub, MailChimp, CodeShip, The Financial Times, UserVoice, Travis CI and many others.

Pusher Real-time Use Cases

Pusher has a number of common use cases for real-time web technologies including:

  1. Activity Streams
  2. Data Visualisations/Dashboards
  3. Notifications & Signalling
  4. Collaborative Apps
  5. Chat
  6. Multiplayer Games

The simplest use case of Pusher is the real time notifications. Whenever something relevant occurs according to the website user’s journey, it automatically pops up a notification for the event. This is the same functionality we have seen on Twitter, Facebook and in many other social media platforms for years.

Notification can also be seen as a form of signaling, as it does not contains any organized representation in the UI of the application, but still triggers a reaction within an application.

As far as the current social web apps are concerned, it is very common to have interactive real time notifications. We have the examples of Facebook, Twitter and other social networking sites, which support integration of creative built-in notification systems within them. In this regard, Pusher is one of the most used and popular services which helps you incorporate real-time notifications to your apps and helps you make them more lively and interactive.

In this blog, I will demonstrate about how to implement real time notification system using Laravel and Pusher.

Prerequisites

For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:

  • Laravel 5.5
  • Pusher

I have decided to host my Laravel application on PHP MySQL hosting. It has great devstack and is known for its highly secured platform. You can also try out Cloudways for free by signing up for an account

Setup your Pusher Account

After successfully completing Laravel installation, now let’s create a Pusher account to get API key and other necessary credentials.

Web Notifications

Setup Pusher in Laravel application

After completing the signup process, carefully note down all the credentials including API key, secret key and others. Then open SSH command interface and write down the following command:

Web Notifications Laravel

.env
Once the composer finishes its process, you can configure Laravel and Pusher. Open the .env file from the root directory of Laravel app and update its values to the desired ones.

// Get the credentials from your pusher dashboard
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=XXXXXXX
PUSHER_APP_SECRET=XXXXXXX

Web Notifications Pusher

Create Notification Event

First of all, you must create an Event class that could broadcast to Pusher from your live Laravel application. Also remember that you can easily eradicate Events from anywhere in the application.

php artisan make:event Notification

The above-mentioned code will create a new Notification class in the app/Events directory. Open the contents of the file and update as shown below:

<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class Notification implements ShouldBroadcast{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $username;
    public $message;

    public function __construct(){
        //your variables
    }

    public function broadcastOn(){
        return ['notification'];
    }
}

In the above-mentioned code, I have created a ShouldBroadcast interface which defines Laravel that the broadcasting of event should be with using whatever driver, which I have configured in the configuration file.

I have also created a constructor which accepts two parameters (username and verb). I have assigned these variables to class properties which also have the same name. Do remember to set the visibility of these properties to public, because they will be ignored if they aren’t set to public.

Lastly, I have set the channel name to broadcast on.

Create Controller

Now let’s create a controller, which will hold notification code logic. Open the SSH command terminal and paste the following command.

.$ php artisan make:controller PusherNotificationController

After successfully creating the controller, paste the following code in controller file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Pusher\Pusher;

class PusherNotificationController extends Controller{

    public function sendNotification(){
        //Remember to change this with your cluster name.
        $options = array(
            'cluster' => 'ap2',
            'encrypted' => true
        );

        //Remember to set your credentials below.
        $pusher = new Pusher(
            'key',
            'secret',
            'app_id', $options
        );

        $message= "Hello Cloudways";

        //Send a message to notify channel with an event name of notify-event
        $pusher->trigger('notification', 'notification-event', $message);
    }
}

It’s time to add Pusher in the controller. You will have to setup cluster and other credentials like secret key, API etc in your controller as well.

Afterwards, you can publish to a channel and can define a specific name for that channel. For this particular tutorial, I have given channel the name of ‘Notification’, and ‘Notification Event’ as the event name. You can also change these names to any other name according to your preference. Do remember to always use the same channel name and event name in your front end clients.

Setup Route

Now I will show you how to add notification route to the web.php file, which I will use to send notifications using Pusher.

//web.php

Route::get('/notification', 'PusherNotificationController@sendNotification');

Create View

Finally after setting up controller and required routes, now let’s move to create view. Working on welcome.blade.php, paste the below following code in your view file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Real-time notifications in Laravel using Pusher</title>

</head>
<body>
    <h1>Real-time notifications using Pusher In Laravel</h1>

    <!-- Incldue Pusher Js Client via CDN -->
    <script src="https://js.pusher.com/4.2/pusher.min.js"></script>
    <!-- Alert whenever a new notification is pusher to our Pusher Channel -->

    <script>
        //Remember to replace key and cluster with your credentials.
        var pusher = new Pusher('key', {
            cluster: 'ap2',
            encrypted: true
        });

        //Also remember to change channel and event name if your's are different.
        var channel = pusher.subscribe('notification');
        channel.bind('notification-event', function(message) {
            alert(message);
        });

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

Now, let’s open up a new tab and visit www.yourdomain/notification while having the www.yourdomain.dev/welcome open in another tab and you should see the alert!.

To see the alert, open a new tab and visit www.yourdomain/notification while having the www.yourdomain.dev/welcome open on one tab. It will definitely show the alert and hence it will confirm the process mentioned in the preceding paragraphs.

Summing Up

In this blog, I have demonstrated how to implement real time notifications in a Laravel app using Pusher. Because Pusher allows us to add more live functionality to our apps and helps make it more interactive, popular social apps like Facebook and Twitter have live web notifications system integrated in their platform. Hence, using Pusher, we can also implement the same functionality in our apps and can enhance the real time interaction while using them.

If you still have more questions regarding this blog, or you want to contribute more on this topic, do feel free to share your thoughts and comments in the comments section below.

The post Web Notifications Using Laravel and Pusher appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/web-notifications-laravel-pusher.html/feed 1 629
How To Create Infinite Scroll Pagination With PHP And Ajax https://www.myprogrammingtutorials.com/infinite-scroll-pagination-with-php-and-ajax.html https://www.myprogrammingtutorials.com/infinite-scroll-pagination-with-php-and-ajax.html#comments Mon, 09 Jul 2018 19:02:44 +0000 https://www.myprogrammingtutorials.com/?p=583 In this tutorial, we are going to learn that how to create infinite scroll pagination with PHP and Ajax. All of you probably must have seen this feature in some websites that you can load more content by just scrolling down. It can be possible via AJAX. I hope all of you guys will be familiar with… Read More »

The post How To Create Infinite Scroll Pagination With PHP And Ajax appeared first on My Programming Tutorials.

]]>
In this tutorial, we are going to learn that how to create infinite scroll pagination with PHP and Ajax.

All of you probably must have seen this feature in some websites that you can load more content by just scrolling down.

It can be possible via AJAX. I hope all of you guys will be familiar with Ajax, if not please see what actually an AJAX is?

Let me show you some live examples of infinite scroll pagination, as you are a regular user of Facebook & Twitter etc. I bet you noticed that they use this kinda pagination. When you scroll down they load more contents on your timeline.

View Demo

infinite scroll pagination with php and ajax

In my previous article, I have covered the pagination with PHP and MySql, If you have not read it yet, then I suggest you read that article first. Because the pagination part will be done by PHP itself.

Requirements to create infinite scroll pagination with PHP and Ajax

1. GIF Loader

I have used Preloaders in this article. Preloader provides almost all type of animated GIF Loaders. It is necessary to show a loading process while fetching data asynchronously.

2. A jQuery plugin called Inview

Inview is a JQuery Plugin, which is designed to fire an event as soon as the targeted element appears on the user’s viewport.

You must have JQuery installed in your page to work with Inview. The important thing is, it works only with jQuery 1.8 & upwards. To learn more about Inview, visit Github jquery.inview.

Usage of Inview

$('#target_element_id').on('inview', function(event, isInView) {
    if (isInView) {

        // element is now visible in the viewport

    } else {

        // element has gone out of viewport

    }
});

Let’s dig into actual coding

1. HTML part

<div id="response">

    <!-- response(next page's data) will get appended here -->

    <!--we need to populate some initial data-->
    <?php
        $conn=mysqli_connect("localhost","my_user","my_password","my_db");
        // Check connection
        if (mysqli_connect_errno()){
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            die();
        }
        $sql = "SELECT * FROM table LIMIT 5";
        $res_data = mysqli_query($conn,$sql);
        while($row = mysqli_fetch_assoc($res_data)){
            echo '<div>Demo'.$row["id"].'</div>';
        }
        mysqli_close($conn);
    ?>

</div>

<input type="hidden" id="pageno" value="1">
<img id="loader" src="loader.svg">

Lets split above HTML snippet and see what actually they will perform. So here we have Three elements #response, #pageno & #loader.

#response element would be the container for our fetched data. We will use AJAX request to fetch next page’s data and append it in #response element.

#pageno is a kind of page number counter, we are using it to identify that how much pages have loaded. We have set its default value to “1” so that it loads the first page first.

#loader will be placed at the last of the results as you can see it in the HTML snippet. When the user scrolls down, the Ajax function that will bring the data of the next page will get fired as soon as the #loader comes in the viewport.

2. AJAX JQuery Part

var nextPage = parseInt($('#pageno').val())+1;

$.ajax({
    type: 'POST',
    url: 'pagination.php',
    data: {
        pageno: nextPage
    },
    success: function(data){
        if(data != ''){							 
            $('#response').append(data);
            $('#pageno').val(nextPage);
        } else {								 
           $("#loader").hide();
        }
    }
});

Every time when #loader appears in the browser’s viewport then the above Ajax function gets fired and sends a POST request to the pagination.php file.

We are sending a nextPage number along with the POST request so that the pagination.php file can understand which page to load.

When execution of the Ajax function gets finished then pagination.php file returns next page’s data. We need to append that data in our #response element as you can see in the above snippet.

3. PHP part

$pageno = $_POST['pageno'];

$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page;

As you can see from here the PHP pagination part has started, as I have suggested earlier you should read my previous article pagination with PHP and MySQL.

The SQL Query for Pagination

$sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";

Let’s assemble the PHP pagination codes

We are going to put all the PHP codes in the pagination.php file, so go ahead and create the pagination.php file and put below codes into it.

<?php

    $pageno = $_POST['pageno'];

    $no_of_records_per_page = 10;
    $offset = ($pageno-1) * $no_of_records_per_page;

    $conn=mysqli_connect("localhost","my_user","my_password","my_db");
    // Check connection
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        die();
    }

    $sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";
    $res_data = mysqli_query($conn,$sql);

    while($row = mysqli_fetch_array($res_data)){

        echo '<div>Demo'.$row["id"].'</div>';

    }

    mysqli_close($conn);

?>

so PHP part has been done here.

Let’s assemble the Html and JQuery codes

<!DOCTYPE html>
<html>
<head>
    <title>Infinite Scroll Demo</title>

    <!-- JQuery CDN -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

    <!-- Inview Js (jquery.inview.js) -->
    <script src="jquery.inview.js"></script>

    <style>
        #response div{
            border: 1px solid lightgrey;
            height: 80px;
            margin-bottom: 5px;
            padding: 50px 0px 0px 0px;
            text-align: center;
        }
        #loader{
            display: block;
            margin: auto;
        }
    </style>
</head>
<body>

    <div id="response">

        <!-- response(next page's data) will get appended here -->

        <!--we need to populate some initial data-->
        <?php
            $conn=mysqli_connect("localhost","my_user","my_password","my_db");
            // Check connection
            if (mysqli_connect_errno()){
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
                die();
            }
            $sql = "SELECT * FROM table LIMIT 5";
            $res_data = mysqli_query($conn,$sql);
            while($row = mysqli_fetch_assoc($res_data)){
                echo '<div>Demo'.$row["id"].'</div>';
            }
            mysqli_close($conn);
        ?>
    </div>

     <input type="hidden" id="pageno" value="1">
     <img id="loader" src="loader.svg">
     <script>
         $(document).ready(function(){
             $('#loader').on('inview', function(event, isInView) {
                 if (isInView) {
                     var nextPage = parseInt($('#pageno').val())+1;
                     $.ajax({
                         type: 'POST',
                         url: 'pagination.php',
                         data: { pageno: nextPage },
                         success: function(data){
                             if(data != ''){							 
                                 $('#response').append(data);
                                 $('#pageno').val(nextPage);
                             } else {								 
                                 $("#loader").hide();
                             }
                         }
                     });
                 }
             });
         });
     </script>
</body>
</html>

That’s all folks!!!, If you find this article helpful, don’t forget to share and subscribe us.

The post How To Create Infinite Scroll Pagination With PHP And Ajax appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/infinite-scroll-pagination-with-php-and-ajax.html/feed 14 583
Create own Cryptocurrency: A Step By Step Guide https://www.myprogrammingtutorials.com/create-own-cryptocurrency.html https://www.myprogrammingtutorials.com/create-own-cryptocurrency.html#comments Mon, 23 Apr 2018 04:11:30 +0000 https://www.myprogrammingtutorials.com/?p=497 In this article, I am going to serve you a detailed information about how to create own Cryptocurrency like Bitcoin and Ethereum. And provide you a step by step guide to set it up on a Live Server as well. What is Cryptocurrency? Cryptocurrency is a kind of digital asset or virtual currency that uses cryptography techniques to secure its… Read More »

The post Create own Cryptocurrency: A Step By Step Guide appeared first on My Programming Tutorials.

]]>
In this article, I am going to serve you a detailed information about how to create own Cryptocurrency like Bitcoin and Ethereum. And provide you a step by step guide to set it up on a Live Server as well.

What is Cryptocurrency?

Cryptocurrency is a kind of digital asset or virtual currency that uses cryptography techniques to secure its transactions.

Bitcoin, Litecoin, Ripple & Ethereum etc. are the best cryptocurrencies in the world. These are frequently called altcoins, as they all are alternative currencies.

There is one more name blockchain technology is very popular in cryptocurrencies network.

What is Blockchain?

Blockchain is simply a decentralized ledger that keeps records of all transactions that take place across peer-to-peer network.

All the transaction’s details are stored in multiple blocks, and each blocks are connected with each other so that they create a chain of blocks that’s why it is called Blockchain.

There is a video by Simply Explained – Savjee which let you understand easily what actually a blockchain technology is.

How To Create Own Cryptocurrency?

1. Creating Block-chain

There are plenty of full featured Open Source Blockchain available out there. Even anyone can fork the existing Bitcoin’s or Litecoin’s blockchain from Github as well.

Actually we are also going to use an open source technology for our block-chain. Because developing a block-chain from scratch is obviously a big deal and it would definitely cost you a huge amount of money.

We are going to use Multichain to create our cryptocurrency. Multichain is an open source blockchain platform provider. You can learn more about Multichain at their official website.

So lets get started :-

Downloading & Installing Multichain Blockchain on our Live Server

As we are going to install our block-chain directly on a live server, so access your server using SSH via putty as administrator (root access) and run following commands one by one.


cd /tmp

wget https://www.multichain.com/download/multichain-1.0.4.tar.gz

tar -xvzf multichain-1.0.4.tar.gz

cd multichain-1.0.4

mv multichaind multichain-cli multichain-util /usr/local/bin

Full instructions for installing multichain’s block-chain are given at their official page here.

Great! we have installed multichain on our server, now its time to create a block-chain. To create it run below command.


multichain-util create ourchain

ourchain is our blockchain’s name you can name your chain whatever you want.

2. making changes in chain

Okay! now our blockchain has been created and we just need to start it. But I recommend you to make changes as per your need in chain before starting it, because blockchain doesn’t allow any amendments when  it gets started.

I know you all are wondering what changes can we make in our blockchain? So I’m listing down some of major parameters you should change as per your need. Although you can always check all the parameters provided by multichain at their blockchain parameters page.

So access your server using SSH via putty as administrator and run below command


nano ~/.multichain/ourchain/params.dat

Following are the parameters you need to work on.

  • chain-description
  • chain-is-testnet
  • first-block-reward (this would be your total coins in your cryptocurrency economy)
  • anyone-can-connect (set it to true)
  • anyone-can-send (set it to true)
  • anyone-can-receive (set it to true)

after making all the required changes you just need to save the params.dat file.

3. starting the blockchain

One you have made changes you are ready to go. So access you server as root (administrator) and run below command to start your chain.


multichaind ourchain -daemon

This command would generate your First Block which is called The Genesis Block.

4. Testing our cryptocurrency.

Access server using SSH via putty as administrator and run below command


multichain-cli ourchain

This command let we enter into interactive mode. For checking chain’s information run getinfo command.

In next article we will learn Blockchain’s operations i.e. to create new wallet address, send coins to other wallets etc. Subscribe us and don’t forget to share this article with your friends.

The post Create own Cryptocurrency: A Step By Step Guide appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/create-own-cryptocurrency.html/feed 1 497
How to use SQL Manager in CodeLobster PHP IDE https://www.myprogrammingtutorials.com/sql-manager-in-codelobster-php-ide.html https://www.myprogrammingtutorials.com/sql-manager-in-codelobster-php-ide.html#respond Thu, 05 Apr 2018 09:15:30 +0000 https://www.myprogrammingtutorials.com/?p=548 Probably, every PHP programmer had to create his own framework or library, and it was necessary to work quickly and do everything practically from scratch. Often we need to test some of our ideas or algorithms and we write code for interacting with databases directly, without using ORM frameworks. In addition, SQL that is used… Read More »

The post How to use SQL Manager in CodeLobster PHP IDE appeared first on My Programming Tutorials.

]]>
Probably, every PHP programmer had to create his own framework or library, and it was necessary to work quickly and do everything practically from scratch.

Often we need to test some of our ideas or algorithms and we write code for interacting with databases directly, without using ORM frameworks.

In addition, SQL that is used in various libraries and CMS might not work quite efficiently and slow down the site.

In such cases, you need to open the SQL editor and start optimizing the queries.

We bring to your attention an article in which the SQL-manager built-in in CodeLobster PHP IDE will be considered.

On a simple example, we will learn how to effectively use the SQL editor and how to create and configure database connections.

Creating and configuring a connection to MySQL

Go to the main menu "Tools" -> "MySQL" -> "SQL Manager". In the opened tab on the right information panel we have the opportunity to add a host and database, for this click the "Register Host" button.

Fill in all the required fields in the dialog box that appears, and straight away let’s give the connection an informative name and enter it in the "Connection Alias" field.

Then we must specify the host and port of our MySQL server and the name of the database with which we are planning to work.

SQL Manager in CodeLobster PHP IDE

It remains to enter the correct username and password and click "OK".

It is done, the host and database are registered and we can begin to examine the functionality of the SQL manager.

Working with tables and data using SQL manager

The main advantage of the built-in CodeLobster SQL manager is the ability to perform the full range of operations necessary for quality work with database.

A classic set of such functions is called CRUD (Create, Read, Update, Delete). You can create and modify tables in the visual mode, add and delete records, as well as read and edit any information.

This, of course, will save a lot of time for the developer at the stage of designing a database for his application.

For our example, we need to create a table in which information about useful books will be stored, and then display this data in a conveniently readable form using a PHP script.

In the program window, right-click on the name of database to which we just connected and select "Create Table" from the context menu. Enter the name of the table – "books" and click "OK".

Now the CodeLobster opens the table editor, in this tab click the "New Field" button.

CodeLobster table editor

In the dialog that appears, enter the name of the field &quot;id&quot;, it will be our primary key with the INTEGER data type, so check "Not Null" and "Autoincrement" checkboxes. The "Primary Key" field will be selected automatically – this is what we need, click "OK".

The next column of the table will contain the name of the book, for this you can use the variable length string – VARCHAR.

CodeLobster table editor

The field is called "title", we set the maximum length for it of 100 characters. Also, adding a book without a name does not make sense, so we set the "Not Null" restriction by enabling the corresponding checkbox.

In addition, check the option "Primary Key", and as a result, MySQL will create an index for this column. Thanks to this, for example, queries with the WHERE title = “…” expression will be executed much faster when you will be working with a table containing a large number of records.

Another thing worth paying attention to is the "Collation" field. Since we have to work with strings in utf8 encoding, we specify the utf8_general_ci collation, since in MySQL this value is used by default for the utf8 character set.

Click "OK" to save the changes.

In the same way, we create three more columns: "author" and "image" of type VARCHAR(100) to store the name of the author of the book and the name of the file with the cover photo, and the "description" column of TEXT type for a brief description of the book.

After the structure is created, we need to press the "Compile" button to execute the commands for creating and saving the table in the database.

CodeLobster table editor

In the program the window in which we are working now has one more tab – "Data", here you can view and edit the contents of the current table.

At the moment, it is still empty, so we will continue to work, press "Insert Record" – this is a button with a "+" sign.

To start, you need to double-click on the desired field in the column and enter the data. In this case, the values of strings and numeric fields are entered directly in place, and for text fields a special dialog box is used, that facilitates and simplifies the input of text in the form of several lines.

CodeLobster php editor

You do not need to enter the "id" column, since its value will be generated automatically by MySQL engine.

Also, do not forget that the real data insertion will occur only after clicking the "Post Edit" button. So, let’s review the values of fields and, if everything is correct, click the button with "check" sign.

So, pretty quickly, you can pre-populate the database and add as many rows as you need for your application.

Working with SQL editor in CodeLobster

Our IDE uses two-panel windows to edit SQL queries. At the top of the window we can enter a query, and at the bottom we can immediately see its result.

Right-click on the table name and select "New SQL File".

In the opened window of the editor, we begin to enter the query, now you can use intelligent prompts not only on the SQL syntax, but also on the names of the tables.

CodeLobster php editor

By pressing Ctrl + Space in the process of composing the query, we also get an auto-complete window on the names of the columns in the current table. Of course, in order to these functions work correctly, a connection to the database must be established.

After we have entered the query, we press the "Execute" button and examine the results at the bottom of the window.

It is possible to save the created file in your project with the extension .sql, as well as the regular file with the source code and use it then at any time.

All the benefits of the SQL editor are also useful if you have to insert queries directly into PHP code.

For our example, we need to run a query to retrieve all the entries from the "books" table. In the image below, you can make sure that CodeLobster does an excellent job with the mixed code.

CodeLobster php editor

It is known that in the development process, the programmer is not limited to creating a database and populating tables.

After the database is designed and filled with data, you can transfer it to another host or save it for later use in other projects.

To start the process of exporting or moving the database, you need to right-click on the name of the database or table and select the "Export" item.

The Export Wizard starts, it has many options and therefore is flexible configured. With its help in several steps you can export to one SQL-file the structure or data contained in tables or them all together.

CodeLobster php editor

In the case of working with individual tables, their contents can be saved not only in the form of SQL, but also in CSV or TSV format, that is very convenient.

Now any other application can work with the exported records, for example, they can be easily analyzed and edited in Microsoft Word or OpenOffice.

So, let’s sum up

We have discussed in detail the use of the SQL manager in CodeLobster IDE.

By studying the article, you learned how to connect to the MySQL server, how to create tables, add entries and execute queries in the editor window or from PHP scripts.

And, finally, you can not be afraid of losing data, because you will be able to quickly backup any database or table with the help of the Wizard.

So, now you have got all the necessary tools for the full range of works on designing databases for your projects.

The post How to use SQL Manager in CodeLobster PHP IDE appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/sql-manager-in-codelobster-php-ide.html/feed 0 548
Generating PDFs with DocRaptor’s HTML-to-PDF Library https://www.myprogrammingtutorials.com/convert-html-to-pdf-with-docraptor-php-library.html https://www.myprogrammingtutorials.com/convert-html-to-pdf-with-docraptor-php-library.html#comments Thu, 08 Mar 2018 11:31:33 +0000 https://www.myprogrammingtutorials.com/?p=525 Many web applications have a PDF export requirement: invoices, reports, brochures, or eBooks. Generating these PDFs, especially if they’re complex or large, can be really challenging. Fortunately, there’s DocRaptor, which provides an easy-to-use API for converting HTML web pages into PDFs. This is a walkthrough of how to setup and use DocRaptor’s PHP library: Installation… Read More »

The post Generating PDFs with DocRaptor’s HTML-to-PDF Library appeared first on My Programming Tutorials.

]]>
convert html to pdf with docraptor php library

Many web applications have a PDF export requirement: invoices, reports, brochures, or eBooks. Generating these PDFs, especially if they’re complex or large, can be really challenging. Fortunately, there’s DocRaptor, which provides an easy-to-use API for converting HTML web pages into PDFs. This is a walkthrough of how to setup and use DocRaptor’s PHP library:

Installation

DocRaptor can be installed via the Composer dependency manager or by downloading the files directly. To use Composer, simply run this on your command line:


composer require docraptor/docrapto

 

Alternatively, download and unzip the latest release into your project directory. Simply include autoload.php to get access to the DocRaptor library:


// docraptor.php
require_once('/path/to/docraptor-php/autoload.php');

 Add Your API Key

Unlimited watermarked test documents can made using the “YOUR_API_KEY_HERE” key. If you’re ready to make non-watermarked documents, you can get your own API key by creating an account.


$configuration = DocRaptor\Configuration::getDefaultConfiguration();
$configuration->setUsername("YOUR_API_KEY_HERE");

Add HTML

To make your PDF, simply set the document content to your HTML:


$docraptor = new DocRaptor\DocApi();
$doc = new DocRaptor\Doc();
$doc->setDocumentContent("<html><body>Your HTML goes here!</body></html>");

 

If you want to use an existing website page, just input the URL like this:


$docraptor = new DocRaptor\DocApi();
$doc = new DocRaptor\Doc();
$doc->setDocumentUrl("http://docraptor.com/samples/ebook.html");

 

Either way you decide to input the HTML, any external assets in your HTML (CSS, JS, images) are required to be accessible to the DocRaptor servers. They must also either have absolute URLs or you can include a baseurl in your document or use the baseurl API option.

Set API Options

Since DocRaptor makes PDFs and Excel files, we need to set the document type:


$doc->setDocumentType("pdf");

 

To create the free watermarked documents, we need to set test to true:


$doc->setTest(true);

 

JavaScript processing can be enabled with this command:


$doc->setJavascript(true);

 

See DocRaptor’s API documentation for the full list of API options. There’s a lot of them, but they aren’t necessary for most projects.

Generate the PDF

That’s all the setup that’s required. Creating the document is just one line of code, but we should wrap it error handling:


try {
    $create_response = $docraptor->createDoc($doc);
} catch (DocRaptor\ApiException $error) {
    echo $error . "\n";
    echo $error->getMessage() . "\n";
    echo $error->getCode() . "\n";
    echo $error->getResponseBody() . "\n";
}

Save the PDF

Once generated, the PDF can be saved to the server.


$file = fopen("/tmp/docraptor-php.pdf", "wb");
fwrite($file, $create_response);
fclose($file);

Or Send it to the Browser

Or if we’re creating the PDF after a user action and we want them to immediately download it, we can send it to the browser without saving it on the server:


header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=example.pdf');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($create_response));
ob_clean();
flush();
echo($create_response);
exit;

Complete Example

Putting it all together, here’s the full code for making a PDF with DocRaptor. As you can see, it’s short and offloads all the CPU intensive work off our server and puts it onto DocRaptor. It also lets us rapidly make PDFs if multiple users request a PDF at once, which is hard to do if we try to use an open source library.


<?php
// docraptor.php
require_once('docraptor-php/autoload.php');
$configuration = DocRaptor\Configuration::getDefaultConfiguration();
$configuration->setUsername("YOUR_API_KEY_HERE");
$docraptor = new DocRaptor\DocApi();
$doc = new DocRaptor\Doc();
$doc->setDocumentContent("<html><body>Hello World</body></html>");
//$doc->setDocumentUrl("http://docraptor.com/examples/invoice.html");
$doc->setDocumentType("pdf"); // DocRaptor also makes Excel files
$doc->setTest(true);
//$doc->setJavascript(true);
try {
    $create_response = $docraptor->createDoc($doc);
    $file = fopen("/tmp/docraptor-php.pdf", "wb");
    fwrite($file, $create_response);
    fclose($file);
    //header('Content-Description: File Transfer');
    //header('Content-Type: application/pdf');
    //header('Content-Disposition: attachment; filename=example.pdf');
    //header('Content-Transfer-Encoding: binary');
    //header('Expires: 0');
    //header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    //header('Pragma: public');
    //header('Content-Length: ' . strlen($create_response));
    //ob_clean();
    //flush();
    //echo($create_response);
    //exit;
} catch (DocRaptor\ApiException $error) {
    echo $error . "\n";
    echo $error->getMessage() . "\n";
    echo $error->getCode() . "\n";
    echo $error->getResponseBody() . "\n";
}

 

Despite PDFs being one of the internet’s most common standards, it’s surprisingly difficult to dynamically create PDFs from a website. There’s three primary tools used to create PDFs:

  • PDF Generators allow you to create PDFs by adding text at pixel location 123×456 and an images at pixel location 456×123. While fast to generate and simple, the code to generate these PDFs is brittle and time consuming to write.
  • Browser-Based libraries use Webkit or Chromium to generate a PDF based on HTML. These are fast to setup, but provide limited PDF functionality and quality. Browsers are simply not optimized from PDF generation.
  • Commercial libraries built from the ground up to turn HTML into PDFs. These engines are designed specifically for PDF generation and provide a level of quality and control than the browser-based libraries cannot.

DocRaptor is based on one of the commercial tools, but they offer affordable pricing and an easy-to-use PHP library.

The post Generating PDFs with DocRaptor’s HTML-to-PDF Library appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/convert-html-to-pdf-with-docraptor-php-library.html/feed 2 525
Install IonCube Loader in Localhost https://www.myprogrammingtutorials.com/install-ioncube-loader-localhost.html https://www.myprogrammingtutorials.com/install-ioncube-loader-localhost.html#comments Sun, 05 Nov 2017 14:32:49 +0000 https://www.myprogrammingtutorials.com/?p=454 Hello developer fellows, in this article, we are going to learn how you can install IonCube Loader in Localhost. Installing an IonCube PHP extension can be quite hard for beginners, but it is not impossible of course. In this topic, I’m going to guide you step by step to install IonCube locally. First of all,… Read More »

The post Install IonCube Loader in Localhost appeared first on My Programming Tutorials.

]]>
Hello developer fellows, in this article, we are going to learn how you can install IonCube Loader in Localhost. Installing an IonCube PHP extension can be quite hard for beginners, but it is not impossible of course. In this topic, I’m going to guide you step by step to install IonCube locally.

First of all, we need to know what exactly the IonCube is? and what exactly it is used for? I know that some of you people will be very familiar with the IonCube, but those who don’t know should read introduction part of this extension.

What is IonCube?

IonCube PHP encoder was founded in 2002. It is a tool that encrypts files written in the PHP programming language (.php files). IonCube’s encryption system is used by PHP developers to protect their program’s source code so that any unauthorized person could not use the program illegally or couldn’t make any changes to files.

What is IonCube Loader?

IonCube Loader is a PHP extension that reads and executes those files that are encrypted by IonCube. If you have encrypted some of your PHP files then you have to install IonCube Loader extension to the server computer. You can use it on your local server too.

Nowadays almost all server computers can be found IonCube installed by default. If you want to figure out whether your server has IonCube installed or not, you can create a phpinfo.php file and search for “Ioncube”. You can also contact your Host Provider to grab such pieces of information.

How to install IonCube Loader in localhost

As I’ve said before, If you want to run a PHP file which is encrypted by IonCube then you should have IonCube installed on your Apache server. In this tutorial, we will cover the installation of the IonCube Loader on a local server such as WAMP, XAMPP, MAMP & LAMP etc.

There is two possible way to install IonCube Loader in Localhost, the first one is manual installation which is pretty hard for beginners, and the second one is installation through a Loader Wizard. We would go with the Loader Wizard because it is the simplest way to install the IonCube Loader.

Carefully read all the steps mentioned below to properly install IonCube Loader in Localhost.

Step-1. Downloading IonCube

Visit IonCube’s official website http://www.ioncube.com/loaders.php and download the Loader Wizard

install ioncube locally

Step-2. Installing IonCube Loader through Loader Wizard

Extract the downloaded file, you will find a loader-wizard.php file there. You have to run this file using your localhost. So put loader-wizard.php file on your localhost and run this file using a browser.

The Loader wizard helps you to find the appropriate package for your computer. Download the Loader suggested by the wizard and after extracting it you will find ioncube folder, you have to paste this folder into C:\wamp\bin\apache\Apache2.4.4\bin\ioncube directory (as per your Apache version).

Step-3 Updating php.ini file

After placing the IonCube Loader in the appropriate directory now it is the time to tell PHP that we’ve installed a new PHP extension, to do so we have to update the php.ini file. You can find this file C:\wamp\bin\apache\Apache2.4.4\bin\php.ini here.

Open php.ini file as administrator and Ctrl + F and search for zend_extension and add the following code just above it


zend_extension = "c:/wamp/bin/apache/Apache2.4.4/bin/ioncube/ioncube_loader_win_5.5.dll"

Note

IonCube zend_extension should the first zend_extension to be loaded in php.ini file. After making changes you have to restart the wamp server.

Checking the IonCube Loader installation

Ater completing all the installation steps, now its time to check whether the installation went well or not.

To check the installation, run the loader-wizard.php file again. If it is installed correctly you will be notified as “Loader Installed”, but if it is not installed correctly then wizard gives some suggestions to install the extension properly, just go the suggestions and make recommended changes.

After completing all the suggestions you will get the Loader Installed notification after executing the loader-wizard.php file.

Install IonCube Loader in WAMP

Above video is a property of John Dugan

I hope that you have learned how to install IonCube Loader in Localhost by this article. In next article, I’ll write about how to encrypt PHP files using IonCube PHP Encoder.

You may also like

The post Install IonCube Loader in Localhost appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/install-ioncube-loader-localhost.html/feed 3 454
How to create Pagination with PHP and MySql https://www.myprogrammingtutorials.com/create-pagination-with-php-and-mysql.html https://www.myprogrammingtutorials.com/create-pagination-with-php-and-mysql.html#comments Mon, 02 Oct 2017 01:06:29 +0000 https://www.myprogrammingtutorials.com/?p=389 In this tutorial, we are going to create pagination with PHP and MySql. It is probably possible that your SQL SELECT query may return result into thousand and millions of records. And it is obviously not a good idea to display all those results on one page. So we can split this result into multiple pages. What… Read More »

The post How to create Pagination with PHP and MySql appeared first on My Programming Tutorials.

]]>
In this tutorial, we are going to create pagination with PHP and MySql. It is probably possible that your SQL SELECT query may return result into thousand and millions of records. And it is obviously not a good idea to display all those results on one page. So we can split this result into multiple pages.

What is Pagination?

Paging means displaying all your fetched results in multiple pages instead of showing them all on one page. It makes that page so long and would take so much time to load.

How to create Pagination with PHP and MySql

MySQL’s LIMIT clause helps us to create a pagination feature. It uses two arguments First argument as OFFSET and second argument the number of records which will be returned from the database.

Follow these simple steps to create pagination in PHP – 

1. Get the current page number

This code will get the current page number with the help of $_GET Array. Note that if it is not present it will set the default page number to 1.


if (isset($_GET['pageno'])) {
    $pageno = $_GET['pageno'];
} else {
    $pageno = 1;
}

 

2. The formula for php pagination

You can always manage the number of records to be displayed in a page by changing the value of $no_of_records_per_page variable.


$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page; 

 

3. Get the number of total number of pages


$total_pages_sql = "SELECT COUNT(*) FROM table";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);

 

4. Constructing the SQL Query for pagination


$sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page"; 

 

5. Pagination buttons

These Buttons are served to users as Next Page & Previous Page, so that they can easily navigate through you pages. Here I am using bootstrap’s pagination button, you can use your own buttons if you want.


<ul class="pagination">
    <li><a href="?pageno=1">First</a></li>
    <li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
        <a href="<?php if($pageno <= 1){ echo '#'; } else { echo "?pageno=".($pageno - 1); } ?>">Prev</a>
    </li>
    <li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
        <a href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
    </li>
    <li><a href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
</ul>

 

6. Let’s assemble all the codes in one page


<html>
<head>
    <title>Pagination</title>
    <!-- Bootstrap CDN -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <?php

        if (isset($_GET['pageno'])) {
            $pageno = $_GET['pageno'];
        } else {
            $pageno = 1;
        }
        $no_of_records_per_page = 10;
        $offset = ($pageno-1) * $no_of_records_per_page;

        $conn=mysqli_connect("localhost","my_user","my_password","my_db");
        // Check connection
        if (mysqli_connect_errno()){
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
            die();
        }

        $total_pages_sql = "SELECT COUNT(*) FROM table";
        $result = mysqli_query($conn,$total_pages_sql);
        $total_rows = mysqli_fetch_array($result)[0];
        $total_pages = ceil($total_rows / $no_of_records_per_page);

        $sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";
        $res_data = mysqli_query($conn,$sql);
        while($row = mysqli_fetch_array($res_data)){
            //here goes the data
        }
        mysqli_close($conn);
    ?>
    <ul class="pagination">
        <li><a href="?pageno=1">First</a></li>
        <li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
            <a href="<?php if($pageno <= 1){ echo '#'; } else { echo "?pageno=".($pageno - 1); } ?>">Prev</a>
        </li>
        <li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
            <a href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
        </li>
        <li><a href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
    </ul>
</body>
</html>

That’s all!

If you find this article helpful, don’t forget to share it with your friends. And stay updated with us by subscribing our blog.

The post How to create Pagination with PHP and MySql appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/create-pagination-with-php-and-mysql.html/feed 72 389
Find Distance Between two Addresses using Google API and PHP https://www.myprogrammingtutorials.com/find-distance-between-two-addresses-google-api-php.html https://www.myprogrammingtutorials.com/find-distance-between-two-addresses-google-api-php.html#comments Wed, 16 Aug 2017 06:27:53 +0000 https://www.myprogrammingtutorials.com/?p=316 In this article, you are going to learn that, how to create a distance calculator sort of module which can find distance between two addresses. We are going to use google map API and PHP to accomplish this task. View Demo The distance calculator module we are going to develop here is basically an API provided by The Google… Read More »

The post Find Distance Between two Addresses using Google API and PHP appeared first on My Programming Tutorials.

]]>
In this article, you are going to learn that, how to create a distance calculator sort of module which can find distance between two addresses. We are going to use google map API and PHP to accomplish this task.

View Demo

The distance calculator module we are going to develop here is basically an API provided by The Google itself. This API can measure the driving distance between two location as well as Travel Time. You can also measure distance between cities using this module.

The format for origin location and destination location could be one of the following:

  • place name (e.g. Bhopal, India)
  • ZIP code (e.g. 462016)
  • latitude/longitude coordinates (e.g. 23.77xxx, 77.30xxx)

to know more about permissible formats please visit Google’s official documentation page.

Find Distance Between two Addresses

Step 1:- Get a google’s API Key from https://developers.google.com/maps/documentation/distance-matrix/get-api-key.

click on GET A KEY button

find distance between two addresses

now click on +create a new project and enter your project name then click on ENABLE API button

distance calculator api

then after you are finally prompted to a popup window containing your API KEY.

calculate distance between two cities

Step 2: source code


<!DOCTYPE html>
<html>
    <body>

        <form action="" method="post">

            <label>Origin:</label> <input type="text" name="o" placeholder="Enter Origin location" required> <br><br>
            <label>Destination:</label> <input type="text" name="d" placeholder="Enter Destination location" required> <br><br>
            <input type="submit" value="Calculate distance & time" name="submit"> <br><br>

        </form>

        <?php
            if(isset($_POST['submit'])){
            $origin = $_POST['o']; $destination = $_POST['d'];
            $api = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$origin."&destinations=".$destination."&key=YOUR_API_KEY");
            $data = json_decode($api);
        ?>

            <label><b>Distance: </b></label> <span><?php echo ((int)$data->rows[0]->elements[0]->distance->value / 1000).' Km'; ?></span> <br><br>
            <label><b>Travel Time: </b></label> <span><?php echo $data->rows[0]->elements[0]->duration->text; ?></span> 

        <?php } ?>

    </body>
</html>

replace YOUR_API_KEY with your API KEY (Step 1) in above code.

We have covered find distance between two addresses module in this article, to get latest updates please subscribe our blog and follow us on Facebook. Don’t forget to share this article with your friends.

You may also like

The post Find Distance Between two Addresses using Google API and PHP appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/find-distance-between-two-addresses-google-api-php.html/feed 30 316
Post into Facebook Page using PHP SDK v5 https://www.myprogrammingtutorials.com/post-into-facebook-page-using-php-sdk-v5.html https://www.myprogrammingtutorials.com/post-into-facebook-page-using-php-sdk-v5.html#comments Sun, 16 Jul 2017 13:49:12 +0000 https://www.myprogrammingtutorials.com/?p=277 In this article, we are going to learn how you can directly post into facebook page using PHP from your website or through your own platform. There are lots of companies available on the Internet which provides such kind of services i.e. Hootsuite, Sproutsocial & Socialbakers etc. Facebook always tries to motivate developers, to build such kind of… Read More »

The post Post into Facebook Page using PHP SDK v5 appeared first on My Programming Tutorials.

]]>
In this article, we are going to learn how you can directly post into facebook page using PHP from your website or through your own platform.

There are lots of companies available on the Internet which provides such kind of services i.e. Hootsuite, Sproutsocial & Socialbakers etc.

Facebook always tries to motivate developers, to build such kind of modules facebook has provided its PHP library for PHP developers called Facebook SDK v5. This SDK is a library with powerful features that enable PHP developers to easily integrate Facebook login and make requests to the Graph API.

Post into Facebook Page using PHP Module

1. Create a Facebook App

1.1 – First we need to create a facebook app in order to use their API, sign in to your Facebook Developers account and click the “Add a New App” or “Get Started“(if you do not have a developers account) link.

1.2 – click on “Settings“, scroll down and you’ll see a “+ Add Platform” just click on it, now it will ask for your website URL, just put your website URL (URL where you want this module to be hosted on) into it.

1.3 – in “Settings” you will see the App ID copy it, we’ll need it further.

1.4 – again in “Settings” you will see the App Secret, to grab it you have to click on show button and have to enter your facebook password.

2. Installing the Facebook PHP SDK

2.1 – First we need to download the Facebook PHP SDK and upload it on your server (website URL, see 1.2), we just need to upload the Facebook directory.

2.2 – create an init.php file and paste below code into it, and replace APP_ID & APP_SECRET with your’s one (see 1.3 & 1.4).


session_start();

require_once('Facebook/autoload.php');

$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.9',
]);

3. The actual code for Post into Facebook Page using PHP

3.1 – create an index.php file, and paste below codes into it.


include('init.php');

$helper = $fb->getRedirectLoginHelper();

$permissions = ['manage_pages','publish_actions','publish_pages'];
$loginUrl = $helper->getLoginUrl('YOUR_WEBSITE_URL/fb-callback.php', $permissions);

echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';

replace “YOUR_WEBSITE_URL” in above code (website URL, see 1.2), as you can see in above code you have to create a fb-callback.php file.

In above code we have to set a callback URL (fb-callback.php), Facebook uses it to send back an access token. So go ahead and create a fb-callback.php file and paste below code into it.


include('init.php');

$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];

try {

  $accessToken = $helper->getAccessToken();

} catch(Facebook\Exceptions\FacebookResponseException $e) {

  echo 'Graph returned an error: ' . $e->getMessage();
  exit;

} catch(Facebook\Exceptions\FacebookSDKException $e) {
  
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;

}

if (! isset($accessToken)) {
  echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.';
  exit;
}

try {

  $response = $fb->get('me/accounts', $accessToken->getValue());
  $response = $response->getDecodedBody();

} catch(Facebook\Exceptions\FacebookResponseException $e) {
  
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;

} catch(Facebook\Exceptions\FacebookSDKException $e) {
  
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;

}

echo "<pre>";
print_r($response);
echo "</pre>";

As of now when we execute our index.php file you will see a “Log in with Facebook!” link there. When you click on that link you will be get redirected to a facebook page. This page asks a user to authorize our app, when they accept it they will get redirected to our fb-callback.php file, Facebook returns the list of all pages administrated by that user, which is stored in “$response” variable.

post into facebook page using php

as you can see above in screenshot, there is individual access_token & id (PageID) available for each page. Finally, these two credentials are required for posting stories on correspondence facebook page.

3.2 – now create a “post.php” file, and paste below codes into it


include('init.php');

$arr = array('message' => 'Testing Post for our new tutorial. Graph API.');

$res = $fb->post('PAGE_ID/feed/', $arr,	'ACCESS_TOKEN');

replace PAGE_ID & ACCESS_TOKEN with your page’s credentials as shown in above screenshot. By running the post.php file you will get something like below.

facebook php sdk

Check out our https://fbautomater.com Facebook Marketing Tool.

Hope you like post into facebook page using PHP module, please subscribe us to get latest updates and news. We are going to post lots of interesting articles in future, please like and share this article with your friends.

You may also like

The post Post into Facebook Page using PHP SDK v5 appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/post-into-facebook-page-using-php-sdk-v5.html/feed 49 277
Facebook like time ago system in php https://www.myprogrammingtutorials.com/facebook-like-time-ago-system-in-php.html https://www.myprogrammingtutorials.com/facebook-like-time-ago-system-in-php.html#comments Fri, 16 Jun 2017 12:06:03 +0000 http://www.myprogrammingtutorials.com/?p=263 In this tutorial, we are going to learn how to make Facebook like time ago system in PHP. In my previous post we have learnt How to close a DIV container when clicking outside using Jquery, I know it’s kinda off topic, because in this topic we are going to learn to convert timestamp to time… Read More »

The post Facebook like time ago system in php appeared first on My Programming Tutorials.

]]>
In this tutorial, we are going to learn how to make Facebook like time ago system in PHP. In my previous post we have learnt How to close a DIV container when clicking outside using Jquery, I know it’s kinda off topic, because in this topic we are going to learn to convert timestamp to time ago in PHP, but it is my duty to expose all those interesting articles so that you can learn more.

Guys If you have used Facebook and you update status on your wall, upload photo or share something on Facebook then after uploading it, It display time as Just Now or you can also see your previous post time, it show like one week or month or year or day ago.

facebook like time ago system in php

Importance of this System (Facebook like time ago system in PHP)

It is common to show dates on the Web in the format such as Published on January 12th, 2017, or 05/17/2017, 09:40:25 and 2017-09-12.

Each of the above examples shows the full date or time of some kind of activity on web applications – be it a published blog article, or a visitor comment, or perhaps an uploaded video.

Showing Date formats like above might seem perfectly reasonable. After all, they are informative and human readable! but “human readable” not at all necessary mean readers will readily be able to understand how recently the activity has occurred or added. The Internet is a fast-moving place, and giving your content a sense of freshness could be the key to engaging with your audience.

Let’s suppose you have stumbled on an article that was published just a couple of hours ago, but the subheading of the article states like:

Published on January 12th, 2017

or

05/17/2017

or

09:40:25

or

2017-09-12

The only problem with above messages is that they do not communicate the feeling that your activity has just been updated. So, surely it is more inviting and much clearer to display the time in this way:

Published 2 hours ago

Strategy And Logics

This function counts the time between the current date and time & previous date and time with simple PHP logic. This function converts the previous date into UNIX timestamp and also the current date in UNIX time. From the difference of this current UNIX timestamp and previous UNIX timestamp, we can get the number of seconds between these dates. From seconds we can easily get minutes, hours, days, weeks, months and years.

Time ago in PHP function


function time_ago_in_php($timestamp){
  
  date_default_timezone_set("Asia/Kolkata");         
  $time_ago        = strtotime($timestamp);
  $current_time    = time();
  $time_difference = $current_time - $time_ago;
  $seconds         = $time_difference;
  
  $minutes = round($seconds / 60); // value 60 is seconds  
  $hours   = round($seconds / 3600); //value 3600 is 60 minutes * 60 sec  
  $days    = round($seconds / 86400); //86400 = 24 * 60 * 60;  
  $weeks   = round($seconds / 604800); // 7*24*60*60;  
  $months  = round($seconds / 2629440); //((365+365+365+365+366)/5/12)*24*60*60  
  $years   = round($seconds / 31553280); //(365+365+365+365+366)/5 * 24 * 60 * 60
                
  if ($seconds <= 60){

    return "Just Now";

  } else if ($minutes <= 60){

    if ($minutes == 1){

      return "one minute ago";

    } else {

      return "$minutes minutes ago";

    }

  } else if ($hours <= 24){

    if ($hours == 1){

      return "an hour ago";

    } else {

      return "$hours hrs ago";

    }

  } else if ($days <= 7){

    if ($days == 1){

      return "yesterday";

    } else {

      return "$days days ago";

    }

  } else if ($weeks <= 4.3){

    if ($weeks == 1){

      return "a week ago";

    } else {

      return "$weeks weeks ago";

    }

  } else if ($months <= 12){

    if ($months == 1){

      return "a month ago";

    } else {

      return "$months months ago";

    }

  } else {
    
    if ($years == 1){

      return "one year ago";

    } else {

      return "$years years ago";

    }
  }
}

You just have to call the function like this:

echo time_ago_in_php(‘2017-06-16 10:57:03’);

So! this is all in facebook like time ago system in PHP module, to learn more programming tricks please share this with your friends, and don’t forget to subscribe our blog because as I said before we are going to post lots of interesting programming tutorials in future, stay tuned.

You may also like

The post Facebook like time ago system in php appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/facebook-like-time-ago-system-in-php.html/feed 1 263
Close or Hide DIV when clicking outside https://www.myprogrammingtutorials.com/close-hide-div-when-clicking-outside.html https://www.myprogrammingtutorials.com/close-hide-div-when-clicking-outside.html#comments Wed, 07 Jun 2017 15:28:31 +0000 http://www.myprogrammingtutorials.com/?p=248 In this tutorial, I’m gonna demonstrate you how to track if a click event is being made outside of an HTML element. Through this example, we are going to close or hide div using Jquery when a click action occurs outside of that element on which the DIV was produced by clicking. If you have ever… Read More »

The post Close or Hide DIV when clicking outside appeared first on My Programming Tutorials.

]]>
In this tutorial, I’m gonna demonstrate you how to track if a click event is being made outside of an HTML element.

Through this example, we are going to close or hide div using Jquery when a click action occurs outside of that element on which the DIV was produced by clicking.

close hide div when clicking outside

If you have ever found with menus boxes that open on click event, but want them to close when a click event occurs  outside of that dom elements.

Here is a simple way to do so. I’m gonna add an event listener to the document’s body.  When someone clicks it, we look for the event’s targeted id. If the ID is same as the box’s div, then we do nothing, if it doesn’t, we fadeOut the menu box.

How to hide div when clicking outside


$(document).mouseup(function (e){

	var container = $("#YOUR_TARGETED_ELEMENT_ID");

	if (!container.is(e.target) && container.has(e.target).length === 0){

		container.fadeOut();
		
	}
}); 

Note: don’t forget to change YOUR_TARGETED_ELEMENT_ID with your targeted element’s ID.

We are using Jquery’s fadeIn() & fadeOut() functions here to hide and show the box. If you want to use Javascript you can set the css property display block to show the box and display none to hide the box.

To learn more interesting Jquery tricks please subscribe us, and share this article.

You may also like

The post Close or Hide DIV when clicking outside appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/close-hide-div-when-clicking-outside.html/feed 4 248
Resize Image Without Stretching in Codeigniter https://www.myprogrammingtutorials.com/resize-image-without-stretching-in-codeigniter.html https://www.myprogrammingtutorials.com/resize-image-without-stretching-in-codeigniter.html#comments Fri, 14 Apr 2017 12:48:27 +0000 http://www.myprogrammingtutorials.com/?p=177 By this article “resize an image without stretching in CodeIgniter” I’m going to show you the mathematics and logic of resizing an image to a different width and height without squeezing or stretching the original image. If the destination image contains a different aspect ratio than the source image, then the source image will be cropped… Read More »

The post Resize Image Without Stretching in Codeigniter appeared first on My Programming Tutorials.

]]>
By this article “resize an image without stretching in CodeIgniter” I’m going to show you the mathematics and logic of resizing an image to a different width and height without squeezing or stretching the original image.

If the destination image contains a different aspect ratio than the source image, then the source image will be cropped in the same ratio of destination image have.

How to resize image without stretching in CodeIgniter

I’m not going to explain about uploading an image as I’m focusing only resizing an image here. In this article the step or module I’m going to explain you have to apply this module after uploading an image, so let’s get started.

paste bellow function in your controller


public function resize_image($image_data){
    $this->load->library('image_lib');
    $w = $image_data['image_width']; // original image's width
    $h = $image_data['image_height']; // original images's height

    $n_w = 273; // destination image's width
    $n_h = 246; // destination image's height

    $source_ratio = $w / $h;
    $new_ratio = $n_w / $n_h;
    if($source_ratio != $new_ratio){

        $config['image_library'] = 'gd2';
        $config['source_image'] = './uploads/uploaded_image.jpg';
        $config['maintain_ratio'] = FALSE;
        if($new_ratio > $source_ratio || (($new_ratio == 1) && ($source_ratio < 1))){
            $config['width'] = $w;
            $config['height'] = round($w/$new_ratio);
            $config['y_axis'] = round(($h - $config['height'])/2);
            $config['x_axis'] = 0;

        } else {

            $config['width'] = round($h * $new_ratio);
            $config['height'] = $h;
            $size_config['x_axis'] = round(($w - $config['width'])/2);
            $size_config['y_axis'] = 0;

        }

        $this->image_lib->initialize($config);
        $this->image_lib->crop();
        $this->image_lib->clear();
    }
    $config['image_library'] = 'gd2';
    $config['source_image'] = './uploads/uploaded_image.jpg';
    $config['new_image'] = './uploads/new/resized_image.jpg';
    $config['maintain_ratio'] = TRUE;
    $config['width'] = $n_w;
    $config['height'] = $n_h;
    $this->image_lib->initialize($config);

    if (!$this->image_lib->resize()){

        echo $this->image_lib->display_errors();

    } else {

        echo "done";

    }
}

after uploading an image you’ve to call above function along with uploaded image data (array)


if($this->upload->do_upload()){
    $image_data = $this->upload->data();
    $this->resize_image($image_data);
}

that’s all you have to do…

Conclusion

This is the more efficient way of “resize image without stretching in CodeIgniter“. All you have to do is just call the resize_image function with the uploaded image data.

For more interesting web development tricks please subscribe us, because we’re going to post lots of web modules and tricks in future.

if you find this article helpful please share it with your friend.

You may also like

The post Resize Image Without Stretching in Codeigniter appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/resize-image-without-stretching-in-codeigniter.html/feed 2 177
Get Users Latitude and Longitude using Google Place API and PHP https://www.myprogrammingtutorials.com/get-users-latitude-and-longitude.html https://www.myprogrammingtutorials.com/get-users-latitude-and-longitude.html#comments Thu, 16 Mar 2017 22:44:35 +0000 http://www.myprogrammingtutorials.com/?p=164 This tutorial is prepared for those Developers who want to get users latitude and longitude. This can be done by many methods, here I’m going to use Google Place API to make such things easier. The method and logic I’m going to use is when user fills the registration form up, we’d capture his city value (Note:… Read More »

The post Get Users Latitude and Longitude using Google Place API and PHP appeared first on My Programming Tutorials.

]]>
This tutorial is prepared for those Developers who want to get users latitude and longitude. This can be done by many methods, here I’m going to use Google Place API to make such things easier.

The method and logic I’m going to use is when user fills the registration form up, we’d capture his city value (Note: city value would be Google Place Search), before proceeding further you have to read my previous post Auto complete Address Search Module Using Google API and PHP, this is the module from which we ask user to enter their location, further this location is used to capture user’s coordinates using another Google API.

It is not all mandatory to use address search module,  you can use manual address as well.

What are Latitude and Longitude?

Latitude and Longitude are the entity that represents the coordinates at the geographic coordinate system.

For example, every actual house has its own address (which includes the house number, the street name, city, country, etc), every single dot on the surface of the earth can be specified by the latitude and longitude coordinates.

Therefore, by using these coordinates we can specify virtually any point on earth.

How to get users latitude and longitude?

Step 1: after submitting registration form catch the user’s current location value (read Auto complete Address Search Module Using Google API and PHP to understand $location variable below).


$location = $_POST['location'];

Step 2: make a request to google place API


 $data = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($location)."&sensor=true");
 
 $longitude = json_decode($data)->results[0]->geometry->location->lng;
 $latitude = json_decode($data)->results[0]->geometry->location->lat;

as you can see the above variables $longitude & $latitude store user’s exact coordinates. You can use these variables as anyway as you want.

NOTE: If you want to store these coordinates into the database, you must have to create longitude and latitude column with datatype double.

Please share this article with your friends, and get in touch because we are going to post lots of interesting and helpful modules in future, don’t forget to subscribe us to get latest updates.

You may also like

The post Get Users Latitude and Longitude using Google Place API and PHP appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/get-users-latitude-and-longitude.html/feed 3 164
Autocomplete Address Search Module Using Google API and PHP https://www.myprogrammingtutorials.com/autocomplete-address-search-module-google-api-php.html https://www.myprogrammingtutorials.com/autocomplete-address-search-module-google-api-php.html#comments Thu, 02 Mar 2017 12:40:14 +0000 http://www.myprogrammingtutorials.com/?p=158 Today I’m going to show you how you can add an autocomplete address search module on your website using Google Place API web service. In our autocomplete address search module we have used a Jquery plugin named Select2, for type and search feature to our module. SEE DEMO HERE Steps to implement an autocomplete address search module… Read More »

The post Autocomplete Address Search Module Using Google API and PHP appeared first on My Programming Tutorials.

]]>
Today I’m going to show you how you can add an autocomplete address search module on your website using Google Place API web service.

In our autocomplete address search module we have used a Jquery plugin named Select2, for type and search feature to our module.

SEE DEMO HERE

Steps to implement an autocomplete address search module

The first step is to grab a google’s API Key, you can find it here.

index.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

    </head>
    <body>

        <select id="address" style="width:500px;"></select>

        <script type="text/javascript">
            $(document).ready(function(){

                $("#submit").click(function(){
                    var val = $("#address").val();
                    alert(val);
                });

                $('select').select2({
                    placeholder: "Search for your city",
                    ajax: {
                        url: function(params){
                            return 'api.php?data='+params.term; 
                        },
                        dataType: 'json', 
                        processResults: function (data) {
                            return {
                                results: $.map(data, function (item) {
                                    return {
                                        text: item.text,
                                        id: item.text
                                    }
                                })
                            };
                        }
                    }

                });
            });
        </script>

    </body>
</html>

 

api.php


<?php

 $terms = $_GET['data'];

 $data = file_get_contents("https://maps.googleapis.com/maps/api/place/autocomplete/json?input=".$terms."&types=geocode&key={YOUR_API_KEY}");


 $arr = array();
 $i=0;
 foreach(json_decode($data)->predictions as $item){
 $arr[$i] = array(
 'id' => $i,
 'text' => $item->description
 );
 $i++;
 }

 echo json_encode($arr);

?>

you just have to put above index.html and api.php in the same directory, and you replace {YOUR_API_KEY} with your’s one.

Important Note

By using google place API google simply needs some policy to follow (read this policy here), Google wants their “powered by Google” logo to be shown in the drop-down.

Note:- you need a live or local server to run this module.

To get latest updates please subscribe us and like our page, we are going to post lots of interesting stuff in future.

You may also like

The post Autocomplete Address Search Module Using Google API and PHP appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/autocomplete-address-search-module-google-api-php.html/feed 9 158
Get User’s Profile With Linkedin API Using PHP https://www.myprogrammingtutorials.com/linkedin-api-using-php-get-users-data.html https://www.myprogrammingtutorials.com/linkedin-api-using-php-get-users-data.html#comments Sun, 26 Feb 2017 01:16:46 +0000 http://www.myprogrammingtutorials.com/?p=141 In this article, we are going to learn how you can get user’s data with LinkedIn API using PHP. There are a couple of social networks which are popular around the world. Sign in with social media is a trendy module on the Internet. Nowadays website visitors or users are getting lazier and lazier, the most… Read More »

The post Get User’s Profile With Linkedin API Using PHP appeared first on My Programming Tutorials.

]]>
In this article, we are going to learn how you can get user’s data with LinkedIn API using PHP. There are a couple of social networks which are popular around the world. Sign in with social media is a trendy module on the Internet.

Nowadays website visitors or users are getting lazier and lazier, the most uncomfortable activity on the Internet is probably “Creating The Account“.

So we need to think about our visitor’s comfort first to make them happier. Because visitors are the most important thing to grow an online business.

get user profile linkedin api using php

There are many popular social sites available which provide API to share their user’s data to make such things easier and comfortable. Such social sites are Facebook, Google, Twitter & LinkedIn. We can use their APIs to collect user’s data automatically without bothering our visitors. In this tutorial, we are focusing on LinkedIn API using PHP to get user’s profile data.

We are going to use LinkedIn Profile API to fetch user’s data from their LinkedIn Account. I recommend you to read all mentioned steps below carefully.

Follow these steps to get user’s profile data with LinkedIn API using PHP

Step 1: Creating Application at LinkedIn’s developer console and setting things up.

Step 1.1: Sign in with your LinkedIn account.

Step 1.2: Visit LinkedIn Developer’s page.

Step 1.3: Click on “Create Application” button.

you have to fill all the mandatory fields of the application form.

sign in with linkedin

after filling the form up you will get redirected to the application’s dashboard page (something like bellow one)

linkedin profile api

now copy the Client ID Client Secret credentials and store it, we will use it further.

Step 1.4 – now you have to check (Checkbox) r_emailaddress option in Default Application Permissions section and update your application by clicking on the update button.

Step 1.5 – now you have to add the 

sign in with social media

 

Step 2: this step contains the actual functionality of API, now we are going to serve a button “Register With LinkedIn” in front of users. When users click on that button they would get redirected to the LinkedIn page, this page asks the user to approve our application, after approval our application can access user’s personal data.

sign in with linkedin

after clicking on “Allow” button users get redirected back to the URL mentioned in Step 1.5:, while this redirection LinkedIn sends some JSON encoded data, this data can be captured easily and can be used as anyway as you want.

Register with LinkedIn Button


<a href="https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URL}&state=987654321&scope=r_basicprofile">Register With LinkedIn</a>

you have to modify button code as per yours.

  • just replace {CLIENT_ID} with your client_id (see Step 1.3 last line)
  • and {REDIRECT_URL} with redirect URL you provided (see Step 1.5)

Step 3: now its time to get the user’s data, suppose I’ve added the redirect URL as http://domain.com/callback.php (in Step 1.5), so callback.php is the file where all the JSON data would be redirected, you can grab user’s data from this file. In below line, I’m going to show how you can capture the redirected JSON Data.

code for the callback.php file is as follow. This is the file whose location (absolute URL of callback.php file) you have added in Step 1.5


if(isset($_GET['code'])){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,"https://www.linkedin.com/oauth/v2/accessToken");
	curl_setopt($ch, CURLOPT_POST, 0);
	curl_setopt($ch, CURLOPT_POSTFIELDS,"grant_type=authorization_code&code=".$_GET['code']."&redirect_uri={REDIRECT_URL}&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$server_output = curl_exec ($ch);
	curl_close ($ch);
}

if(isset($_GET['code']) && json_decode($server_output)->access_token != ''){

     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL,"https://api.linkedin.com/v1/people/~?oauth2_access_token=".json_decode($server_output)->access_token."&format=json");
     curl_setopt($ch, CURLOPT_POST, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $server_output2 = curl_exec ($ch);
     curl_close ($ch);

     $user_data = json_decode($server_output2);

     print_r($user_data);

}

so all the user’s data finally get stored in the $user_data variable. You can now store these details in a database as well.

If you find this tutorial helpful please don’t forget to share it with your friends because sharing is a caring!

You may also like

The post Get User’s Profile With Linkedin API Using PHP appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/linkedin-api-using-php-get-users-data.html/feed 26 141
Multi Level Nested Category System in Codeigniter and MySql https://www.myprogrammingtutorials.com/multi-level-nested-category-system-codeigniter-mysql.html https://www.myprogrammingtutorials.com/multi-level-nested-category-system-codeigniter-mysql.html#comments Wed, 22 Feb 2017 13:23:26 +0000 http://www.myprogrammingtutorials.com/?p=135 Hello, today we are going to discuss on multi level category system in CodeIgniter which is a very common and essential module or feature of any e-commerce websites or any website. Creating nested category system is not as easy as you think, but it is not impossible too. Here I am going to deliver full… Read More »

The post Multi Level Nested Category System in Codeigniter and MySql appeared first on My Programming Tutorials.

]]>
Hello, today we are going to discuss on multi level category system in CodeIgniter which is a very common and essential module or feature of any e-commerce websites or any website.

Creating nested category system is not as easy as you think, but it is not impossible too. Here I am going to deliver full step by step tutorial on how you can create such kind of module using Codeigniter & MySql.

How to create Multi Level Category System in Codeigniter

This module is based on the recursive function concept. So let’s get started to develop multi level nested category system, carefully read below steps mentioned.

I am assuming that you are familiar with CodeIgniter’s MVC structure, so I’m not going to explain what model and controller in CI are.

1. create the database structure for categories table and insert all the data as shown in below image

multi-level-category-system

SQL code for categories table, open SQL tab in PhpMyAdmin and run below code.


CREATE TABLE `categories` (
  `cat_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `cat_name` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `parent_id` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

2. creating model functions


    public function get_categories(){

        $this->db->select('*');
        $this->db->from('categories');
        $this->db->where('parent_id', 0);

        $parent = $this->db->get();
        
        $categories = $parent->result();
        $i=0;
        foreach($categories as $p_cat){

            $categories[$i]->sub = $this->sub_categories($p_cat->cat_id);
            $i++;
        }
        return $categories;
    }

    public function sub_categories($id){

        $this->db->select('*');
        $this->db->from('categories');
        $this->db->where('parent_id', $id);

        $child = $this->db->get();
        $categories = $child->result();
        $i=0;
        foreach($categories as $p_cat){

            $categories[$i]->sub = $this->sub_categories($p_cat->cat_id);
            $i++;
        }
        return $categories;       
    }

3. creating controller function


    public function categories(){

        $this->load->model('model_categories');
	$data = $this->model_categories->get_categories();

	print_r($data);
    }

if you are done with everything right as I mentioned in this brief tutorial, then after running the controller’s “categories()” function should produce the following result-

multi-level-category-system

in controller “categories()” function the variable $data stores all the categories available in your categories table. As you can see $data is an array, you can easily parse this array into any multi level menu item or lists.

If you find this article helpful please don’t get shy to share this article with your friends.

You may also like

The post Multi Level Nested Category System in Codeigniter and MySql appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/multi-level-nested-category-system-codeigniter-mysql.html/feed 41 135
Track User’s Real IP Address https://www.myprogrammingtutorials.com/track-users-real-ip-address.html https://www.myprogrammingtutorials.com/track-users-real-ip-address.html#comments Sun, 19 Feb 2017 03:41:09 +0000 http://www.myprogrammingtutorials.com/?p=127 Hello Readers! In this article, we are about to learn how you can capture your website visitor’s Real IP Address using PHP. First of all, we need to know what actually an IP address is? Track Real IP address of website visitors using PHP Following snippet of PHP code would help you to catch the visitor’s… Read More »

The post Track User’s Real IP Address appeared first on My Programming Tutorials.

]]>
Hello Readers! In this article, we are about to learn how you can capture your website visitor’s Real IP Address using PHP. First of all, we need to know what actually an IP address is?

Track Real IP address of website visitors using PHP

Following snippet of PHP code would help you to catch the visitor’s real IP address even they are surfing your website through a proxy.


if(!empty($_SERVER['HTTP_CLIENT_IP'])){
    $ip=$_SERVER['HTTP_CLIENT_IP'];
} else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){

    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];

} else {

    $ip=$_SERVER['REMOTE_ADDR'];

}

I’m sure you are willing to know everything about above snippet of codes, and what each code do? No worry I am going to explain everything about it further.

What is an IP Address?

IP stands for Internet Protocol. An IP is a group of numeric digits separated by dots. IP gets allotted to every machine (computer device) which is connected to computer networks which use the Internet Protocol (TCP/IP) for their communications.

An IP is a unique identification that almost every computing device (personal computers, smartphones, tablets etc.) have to identify themselves in an IP-based network to communicate with other computing devices.

In an IP network, every device must have their own and unique IP address. Similar to Home or any physical location or place which have their own physical address.

Tow types of IP addresses are being used today in abundance, these are IPv4 and IPv6.

IPv4

The IPv4 is made up of 4 groups of digits, which are divided by 3 dots, each group can be between 0 – 255. For example, IP address of MPT(www.myprogrammingtutorials.com) is 198.54.116.175. This is the unique identification number which is used to identify MPT Blog on the Internet.

IPv6

An IPv6 address format is totally different than the format of IPv4. It is made up of 4 hexadecimal digits separated by colons (“:”). It looks something like “2405:204:e201:df32:1d15:8e4a:8c61:65b“.

Why it is required to track user’s IP address

Tracking the IP address is a very important requirement for any applications or scripts where we store the users or visitors details. For security reason, we can store IP address of our website visitors who are doing any purchases or performing any type of online transaction. We can use the IP to find out the geographical location of the visitors. Sometimes based on the IP we can redirect the browser to different areas of the site.

I’m sure you have heard about Google Analytics. It is web analytics service provided by The Google launched in November 2005. It uses IP to track the visitors.

There are many positive reasons available which inspire owners to track their visitors IP, such as:

  • Traffic analytics (to know how your website is performing in other countries)
  • user’s or visitor’s details if any security problem occurs
  • for knowing which Geolocation is performing well in the terms of getting traffic.

However, Cybercrime is increasing day by day in the age of the Internet. It is highly required you to know all about your clients or visitors of your website or blog.

How to get User’s IP Address

Lots of IP tracker available out there. You can use www.google.com as well to find your IP address, just navigate google’s page and search for “my IP” keyword.

my-ip

But in this article, we are discussing how to fetch user’s IP address programmatically. The programming language we are going to use here is PHP. PHP is a Server Side scripting language which is widely used to develop web applications.

However, every server-side language has their own inbuilt methods to capture an IP address. PHP uses $_SERVER['REMOTE_ADDR'] variable to store an IP address.

We all know that getting the IP of the visitors is a quite simple job using PHP, even in other programming languages. But are you sure that you are getting the original IP of the user?

In PHP, $_SERVER['REMOTE_ADDR'] is used to get the user’s IP. But what happens if any user which currently surfing your website from the USA via the proxy server of Germany. In this case, $_SERVER[‘REMOTE_ADDR’] will return IP of the Germany rather than IP of USA.

We can use the following environment variables to get visitor’s IP:

With Proxy detection, this would return the real IP address of visitors.


$_SERVER['HTTP_X_FORWARDED_FOR'];

 

No Proxy detection, this would return the proxy IP address.


$_SERVER['REMOTE_ADDR'];

Note:

If you want to store IP address in a database, I highly recommend to store it as a string with space of at least 45 characters. Because IPv6 is taking place of IPv4, as it is a newer version. IPv6 contains a maximum length of 39 characters and IPv4-mapped IPv6 address contains a maximum length of 45 characters.

You may also like

The post Track User’s Real IP Address appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/track-users-real-ip-address.html/feed 2 127
Split Unordered List Into Multiple Columns using CSS3 Columns Property https://www.myprogrammingtutorials.com/unordered-list-into-multiple-columns.html https://www.myprogrammingtutorials.com/unordered-list-into-multiple-columns.html#respond Wed, 08 Feb 2017 12:54:19 +0000 http://www.myprogrammingtutorials.com/?p=111 In this article, we are going to learn how to split the unordered list into multiple columns using pure CSS3 Property column-count. What is CSS3 “column-count”? column-count is a CSS3 property, it is used to split list elements into multiple columns and to develop a multi-column and single column layout as well. It is supported by almost… Read More »

The post Split Unordered List Into Multiple Columns using CSS3 Columns Property appeared first on My Programming Tutorials.

]]>
In this article, we are going to learn how to split the unordered list into multiple columns using pure CSS3 Property column-count.

What is CSS3 “column-count”?

column-count is a CSS3 property, it is used to split list elements into multiple columns and to develop a multi-column and single column layout as well. It is supported by almost all latest Browsers.

However, every CSS3 Property uses some predefined prefix for individual browsers, some of them are mentioned below.

-moz- Prefix is used for Mozilla Firefox, so the final code would be -moz-column-count

-o- is used for Opera, so the final code would be -o-column-count

 -webkit- is used for Safari, so the final code would be -webkit-column-count

Chrome doesn’t need any prefix, so you can use directly as column-count

Why use column-count?

column-count is a very useful property provided by CSS3. It reduces lots of efforts while designing a web page. If you are a Web Designer then this code would help you while creating multi-column blocks with fewer CSS codes.

As you all know that huge amounts of CSS codes increase the load time, which is definitely not good for any website. It increases the size of a website. According to Google, a web page should have its size less than 500KB, it helps Google Crawler to crawl your website faster.

Load Time is one of the major factors for Google Ranking. If you want your website to rank well in Google Search then you must keep your website’s load time as minimum as you can.

Google always says that “you take care of my visitors then I’ll take care of your’s“, Google is very strict about his visitors. Google wouldn’t rank you better if your website doesn’t have a good user experience.

It is always a good idea to keep your website’s load time minimum. It gives the user a good experience to navigate through your website.

suppose, when you have a lot of lists to show on a single page then it is always good to split that list into multiple columns. It increases the professionalism and look and feel as well.

Ordered & Unordered Lists

Ordered List (<ol>) is an HTML element, which is used to generate an ordered list in a web page. By default, this element displays a simple conventional vertical list, which looks something like below.

  1. List Item 1
  2. List Item 2
  3. List Item 3
  4. List item 4

as you can see above list, it is displaying digits to order their lists. However, you can change its order type by using the type Attribute, here is a full demonstration to do so.

Unordered List (<ul>) is also an HTML element, which is used to generate bullet lists. By default, it displays a verticle list with no order, that’s why it is called unordered list, below is a conventional look of the unordered list element.

  • List Item 1
  • List Item 2
  • List Item 3
  • List Item 4

Can we style our List elements with multi-column CSS property?

The answer is Yes!, we can style List elements with the CSS3 column-count property. However, we can apply this property to any block level elements.

You can use this property for media queries also to set the width of the column automatically. Suppose you need to control column-count depending on the website with you can use media queries here.

In our future post, we definitely talk about how to use this property to other elements, in this post, I am going to focus on List elements only.

Below is an unordered list (<ul>) demonstrated in 4 lines, as you can see lists are arranged in 4 columns, not in their conventional long vertical look.

css3 multi column

As you can see above, lists are divided into 4 cols, you can make cols as much as you want. You just have to increase the property value. For above list, I have used column-count:4;

If you want your list to be divided into 6 cols then your code should be,column-count:6; don’t forget to add the browser-specific prefix if you want your web page supports all browsers.

How to make the unordered list into multiple columns?

As you know CSS can be applied using 3 Methods which are Internal, External & Inline CSS. You can apply this code to any of three methods.

But I strongly recommend you to use External CSS Method only. When it comes to On-Site Optimization it would be good to separate all your CSS & HTML codes.

Following is a combined code you should go with. You can use this snippet as your External CSS or Internal CSS as well.


li{
 -webkit-column-count: 4;
 -moz-column-count: 4;
 -o-column-count: 4;
  column-count: 4; 
} 

Related Properties

  • columns
  • column-fill
  • column-gap
  • column-rule
  • column-span
  • column-width

Conclusion

A Huge amount of codes is not good enough to provide the user a good experience, there is always a simple way to do so. So keep your codes as simple and minimum as you can.

You may also like

The post Split Unordered List Into Multiple Columns using CSS3 Columns Property appeared first on My Programming Tutorials.

]]>
https://www.myprogrammingtutorials.com/unordered-list-into-multiple-columns.html/feed 0 111