Wednesday, 16 October 2019

Laravel 6 Crud Application using Yajra Datatables and Ajax

Part 1 - How to Implement Yajra Datatables in Laravel 6




Part 2 - How to Insert data into Mysql in Laravel 6 using Ajax with Bootstrap Modal




Are you looking for web tutorial on Laravel 6 framework, then you have come on the right place, because in this post, you can learn how to make Single page Crud application in Laravel 6 framework by using Yajra Datatables package and Ajax. This framework version has been release in the month of September 2019. This framework has required your PHP version must be greater than 7.2. There are following changes has done in Laravel 6 framework.

  1. String & Array Helpers Moved To Package
  2. Carbon 2.0 Supported
  3. Added cursor method in Eloquent
  4. Update on Eloquent BelongsTo::update Method
  5. Declaration Of Primary Key Type

For learn any framework version, first you need to have learn some basic operation like CRUD (Create, Read, Update, Delete). So, you can understand, how can we perform database insert, update, delete, select data operation. This is our first post on Laravel 6 framework.

So, here we have make Single Page Crud Application in which we have use Yajra Datatables package with Ajax. So, here you can also learn how to use Yajra Datatables package with Laravel 6 framework. Here also we have use Ajax, so you can perform all operation like Add, Edit and Remove data operation on same page like Desktop application. That means by using Ajax using make web application working like Desktop application, this is because all operation will be done on client side, and only database related request has been send to server. So, Database related operation will be done without refresh of web page. Below you can find step by step process for how to use Ajax and Yajra Datatables package in Laravel 6 for make Crud Application with Mysql database.

  1. Create Table in Database
  2. Download and Install Laravel 6 framework
  3. Download & Install Yajra Datatables package
  4. Create Model Class
  5. Create Controller in Laravel 6
  6. Create Blade File in Laravel 6
  7. Set Route in Laravel 6
  8. Run Laravel 6 Application






Create Table in Database


Run following sql script in your database. It will make sample_datas table in your define database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `sample_datas`
--

CREATE TABLE `sample_datas` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `sample_datas`
--

INSERT INTO `sample_datas` (`id`, `first_name`, `last_name`, `created_at`, `updated_at`) VALUES
(1, 'John', 'Smith', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(2, 'Peter', 'Parker', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(3, 'Larry', 'Degraw', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(4, 'Tabitha', 'Russell', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(5, 'Susan', 'Diener', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(6, 'William', 'Batiste', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(7, 'Bessie', 'Tucker', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(8, 'Eva', 'King', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(9, 'Dorothy', 'Hays', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(10, 'Nannie', 'Ayers', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(11, 'Gerald', 'Brown', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(12, 'Judith', 'Smith', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(13, 'Betty', 'McLaughlin', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(14, 'Delores', 'Schumacher', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(15, 'Gloria', 'Romero', '2019-10-14 06:30:00', '2019-10-14 06:30:00'),
(16, 'Bobbie', 'Wilson', '2019-10-14 06:30:00', '2019-10-14 06:30:00'),
(17, 'Paul', 'Pate', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(18, 'Ryan', 'Hoang', '2019-10-14 13:30:00', '2019-10-14 13:30:00');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `sample_datas`
--
ALTER TABLE `sample_datas`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_datas`
--
ALTER TABLE `sample_datas`
  MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;


Download and Install Laravel 6 framework


First we need to download Laravel 6 framework, so for download we have use composer, because this framework dependncy has been manage by composer. For this we have go to command prompt and then after go to directory in which we want to download Laravel 6 framework. After this we have to run composer command and then after we have to learn following command.


composer create-project --prefer-dist laravel/laravel laravel-6


This command will make laravel-6 folder in define directory and in that it will download Laravel 6 framework. So this way we can download Laravel 6 framework.

Download & Install Yajra Datatables package


Here we have use Yajra Datatables package with Laravel 6 framework. So for this we have to download and install Yajra Datatables package. For this we have to go command prompt and run following command.


composer require yajra/laravel-datatables-oracle


This command will download the Yajra Datatables compatible version with Laravel 6 framework. Now we want to publish it. For this we have to open config/app.php file and in this file we have to define service providers details and class aliases details which you can find below.


<?php

--------

'providers' => [

---------

Yajra\DataTables\DataTablesServiceProvider::class,

---------

],

'aliases' => [

---------

'DataTables' => Yajra\DataTables\Facades\DataTables::class,

---------

],

--------

?>


Create Model Class


In Laravel 6 framework, here we have use Model class for make crud application. For this we have go to command and run follwing command.


php artisan make:model Sample_data --migration


This command will make Model class file in app folder with name like Sample_data.php. In this file we have to define table column name for database related operation which you can find below.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Sample_data extends Model
{
    protected $fillable = [
     'first_name', 'last_name'
    ];
}


Create Controller in Laravel 6


In Laravel 6 controller has been used for handle http request of application. In Laravel 6 controller class has been store in app/Http/Controllers folder. Here want to create Crud controller, that means in this controller class all crud operation method inbuild made at the time of creating class. For create controller file in Laravel 6, we have to go command prompt and write following command.


php artisan make:controller SampleController --resource --model=Sample_data


Above command will make SampleController.php file in app/Http/Controllers folder. In this controller class first we want to import Datatables class. For this we have to write use DataTables; this statement, it will import Yajra Datatables package class in this controller class.

In this class following crud method has been inbuild made at the time of creation of class.

index(Request $request) - This is the root method of this class, this method has been used for displaying data from database. In this method we have check first any ajax request has been received or not. If any ajax request has been received, then it will used Sample_data.php modal class for fetch latest data from Mysql database and then after it has use Yajra Datatables package for load data in jQuery Datatables plugin. On without ajax request it has load sample_data.blade.php view file in browser.
store(Request $request) - This store() method has been received ajax request for add or insert data into Mysql table. In this method first it has validate form data by using Validator class. If any validation error has occur then it has send error response to Ajax request. But suppose there is no any validation has found in form data then it has proceed for insert new record in Mysql table by using Model class and after successfully inserting of data into database then it has send success response to ajax request.

app/Http/Controllers/SampleController

<?php

namespace App\Http\Controllers;

use App\Sample_data;
use Illuminate\Http\Request;
use DataTables;
use Validator;

class SampleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if($request->ajax())
        {
            $data = Sample_data::latest()->get();
            return DataTables::of($data)
                    ->addColumn('action', function($data){
                        $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
                        $button .= '&nbsp;&nbsp;&nbsp;<button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
                        return $button;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
        return view('sample_data');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = array(
            'first_name'    =>  'required',
            'last_name'     =>  'required'
        );

        $error = Validator::make($request->all(), $rules);

        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }

        $form_data = array(
            'first_name'        =>  $request->first_name,
            'last_name'         =>  $request->last_name
        );

        Sample_data::create($form_data);

        return response()->json(['success' => 'Data Added successfully.']);

    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Sample_data  $sample_data
     * @return \Illuminate\Http\Response
     */
    public function show(Sample_data $sample_data)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Sample_data  $sample_data
     * @return \Illuminate\Http\Response
     */
    public function edit(Sample_data $sample_data)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Sample_data  $sample_data
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Sample_data $sample_data)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Sample_data  $sample_data
     * @return \Illuminate\Http\Response
     */
    public function destroy(Sample_data $sample_data)
    {
        //
    }
}



Create Blade File in Laravel 6


In Laravel 6 framework blade file has been store in resources/views folder. Generally in Laravel 6 blade file has been used to display HTML output in browser. Here we have create sample_data.blade.php blade file for this single page crud application. In this file, we have already imported required library for use jQuery Datatables plugin, jquery and Bootstrap.

In this file, first we have create one HTML table defination with three table column with id is equal to user_table. Based on this id value, we will initialize jQuery Datatable plugin, which you can find in jquery code below.
Here we have use Bootstrap modal for form. Because here we want to make single page application, so by using Bootstrap modal we can add new data by using modal form.

For submit form data, here we have use Ajax request. When we have submit form data then at that time Ajax request has been send to store() method of SampleController.php file.
resources/views/sample_data.blade.php


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>How to Insert data into Mysql in Laravel 6 using Ajax with Bootstrap Modal</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">How to Insert data into Mysql in Laravel 6 using Ajax with Bootstrap Modal</h3>
     <br />
     <div align="right">
      <button type="button" name="create_record" id="create_record" class="btn btn-success btn-sm">Create Record</button>
     </div>
     <br />
   <div class="table-responsive">
    <table id="user_table" class="table table-bordered table-striped">
     <thead>
      <tr>
       <th width="35%">First Name</th>
                <th width="35%">Last Name</th>
                <th width="30%">Action</th>
      </tr>
     </thead>
    </table>
   </div>
   <br />
   <br />
  </div>
 </body>
</html>

<div id="formModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Add New Record</h4>
        </div>
        <div class="modal-body">
         <span id="form_result"></span>
         <form method="post" id="sample_form" class="form-horizontal">
          @csrf
          <div class="form-group">
            <label class="control-label col-md-4" >First Name : </label>
            <div class="col-md-8">
             <input type="text" name="first_name" id="first_name" class="form-control" />
            </div>
           </div>
           <div class="form-group">
            <label class="control-label col-md-4">Last Name : </label>
            <div class="col-md-8">
             <input type="text" name="last_name" id="last_name" class="form-control" />
            </div>
           </div>
                <br />
                <div class="form-group" align="center">
                 <input type="hidden" name="action" id="action" value="Add" />
                 <input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="Add" />
                </div>
         </form>
        </div>
     </div>
    </div>
</div>


<script>
$(document).ready(function(){

 $('#user_table').DataTable({
  processing: true,
  serverSide: true,
  ajax: {
   url: "{{ route('sample.index') }}",
  },
  columns: [
   {
    data: 'first_name',
    name: 'first_name'
   },
   {
    data: 'last_name',
    name: 'last_name'
   },
   {
    data: 'action',
    name: 'action',
    orderable: false
   }
  ]
 });

 $('#create_record').click(function(){
  $('#formModal').modal('show');
 });

 $('#sample_form').on('submit', function(event){
  event.preventDefault();
  var action_url = '';

  if($('#action').val() == 'Add')
  {
   action_url = "{{ route('sample.store') }}";
  }

  $.ajax({
   url: action_url,
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   success:function(data)
   {
    var html = '';
    if(data.errors)
    {
     html = '<div class="alert alert-danger">';
     for(var count = 0; count < data.errors.length; count++)
     {
      html += '<p>' + data.errors[count] + '</p>';
     }
     html += '</div>';
    }
    if(data.success)
    {
     html = '<div class="alert alert-success">' + data.success + '</div>';
     $('#sample_form')[0].reset();
     $('#user_table').DataTable().ajax.reload();
    }
    $('#form_result').html(html);
   }
  });
 });

});
</script>


Set Route in Laravel 6


In this step we have to set the route for all SampleController.php file. For this we have to open routes/web.php file. And this file we have set route for all method of SampleController.php file.


<?php

Route::resource('sample', 'SampleController');

?>


Above code will set the route of all method of SampleController.php class.

Run Laravel 6 Application


So, here our all code is ready, now we want to run Laravel 6 application. For this we have to go command prompt and write following command.


php artisan serve


This command will start laravel application, and it will return base url of your Laravel 6 application. For run above code you have to write following url in your browser.


http://127.0.0.1:8000/sample

By above url, you can check your first crud application which has been make in Laravel 6 framework, by using Yajra Datatables package and Ajax. Remaining source code will be updated very soon.






Tuesday, 15 October 2019

Learn How to Easily Fix the 500 Internal Server Error In WordPress site


Although you may get stressed up or frustrating once you see an inside server error on your web site, the largest goal here is to reverse engineer the error and stop it from occurring again.

One of the most issues with the interior server error or error 500; isn't knowing what's inflicting the error. Basically, you're attempting to create an informed guess on the supply of the error.

As you may usually establish, the interior server error is one of the most common errors in WordPress which will be difficult to repair. If you're presently experiencing internal server error on your website, this text can assist you resolve it and acquire your website back.

Table of Contents


  • Backup Your Site (Caution)

  • cPanel Backup Option

  • Reverse Recent Site Changes

  • Filezilla FTP Client Solution

  • Common Possible Sources of Internal Server Error

  • Easy and Simple Solutions to Fix Internal Server Error

  • WordPress Themes Problem

  • Disable WordPress Themes via FTP Client – Filezilla

  • Disable WordPress Themes via cPanel File Manager

  • WordPress Plugins Conflicts

  • Disable WordPress Plugins via FTP Client – Filezilla

  • Disable WordPress Plugins via cPanel

  • Increase the PHP Memory Limit

  • Corrupted .htaccess

  • Web Host Server Side Problem – Last Resort


Backup Your Site (Caution):



As a warning, it's extremely suggested that you simply begin by making an entire backup of your website since in most cases you're not alert to the source of internal server error.

Backing up your website is necessary to avoid loss of information as you are trying to resolve the inner server error. making a full web site backup is extremely easy; the subsequent are fast choices you'll be able to use to make the backup of your site.

cPanel Backup Option:


You can use your net hosting cPanel dashboard to make a backup of your web site. you must log into your cPanel dashboard and once there, search for the backup option.

In most standard cPanels, you'll find the backup option or a backup wizard with an icon or a link as shown within the image below:


Although each net host may have a unique kind of cPanel dashboard configuration, sometimes every net host has some style of a backup button, or link to permit you to make a manual backup of your web site.

If you probably did not see this feature otherwise you are experiencing issues, simply contact your net hosting supplier to raise regarding the backup choices available.

As an alternative, if you have got FTP access to your web site, you'll be able to easily log in and download your web site files on to your pc.

Reverse Recent Site Changes:


Once you're able to begin troubleshooting your web site, let ME offer you a fast suggestion – you'll remember the changes you've got recently created on your website that might be causing the internal server error. Reversing recent changes is a smart place to get started since you'll see if it resolves the error.

The recent changes may be a replacement plugin you additional, a modification of the active WordPress theme or any edit done on the WordPress core files.

Think of the last modification on your site; did you update a theme or a plugin?

You may have put in or updated a plugin and before the modification, your web site was operating perfectly but once the update, the 500 internal server error occurred. If you recognize it's a plugin or a theme, this may assist you resolve the error quickly.

If you can not find out if it’s the recent changes causing the error, let’s start with different choices.

To start fixing this error, you wish full access to the WordPress files on your web site.

Filezilla FTP Client Solution:


Filezilla is a free FTP consumer resolution that you simply will use to upload and download files from your net server. Filezilla is simple to use, and it's free for you to download and install on your laptop.


Filezilla is also nice for merging files and uploading the unified files on your server. you'll additionally discuss with your internet hosting supplier to inquire about the FTP solutions that may be included along with your internet hosting services. The image below is the associate example of the FTP consumer solutions offered by an internet host.


If something, inquire regarding the FTP logins available or set them from the cPanel. Check on your cPanel for the FTP accounts option or a wizard that you simply will use to make and FTP accounts. the bulk of net hosting corporations have this feature or link available on the cPanel dashboard.

Common Possible Sources of Internal Server Error:


Internal server error doesn't have one specific cause but, rather there are many incidences that may result in an inside server error.

Now we want to decide on the foremost probably sources of internal server error; these sources will include:

WordPress themes problem.
WordPress plugins conflicts.
Exhausted PHP memory limits.
Corrupted .htaccess file.
Web host server-side problems.

Let us examine each of those potential causes of 500 internal server errors and description the particular solutions to assist you to fix each of those causes of this error.

Easy and Simple Solutions to Fix Internal Server Error:


Without the error giving us a selected origin of the interior server error, we are primarily using the trial and error approach to seek out an answer.

Let us look into each of those sources and their simple solutions. Again, if you've got a sense you recognize the reason behind the error, you will wish to easily try that solution first.

WordPress Themes Problem:


A WordPress theme makes a WordPress website look professional, however, in some instances, a WordPress theme may be the source of your error 500. you need to, therefore, disable all the put in WordPress themes, one by one excluding the default WordPress theme.

Disable WordPress Themes via FTP Client – Filezilla:


To disable themes, easily login to your FTP consumer and located the wp-content folder of your WordPress web site and inside the wp-content folder, navigate to themes folder wherever you'll find all the themes put in on your web site.

File Path – public_html > wp-content > themes



Once you're inside the themes folder, you'll be able to currently begin renaming the themes one by one. Renaming themes on Filezilla is extremely easy; you simply got to right-click on the theme and opt for the ‘Rename’ option.


You can rename the theme to any name, however, the best practice is to feature AN underscore and also the name ‘old’ for you to remember the identity of the theme after renaming all the themes.

Disable WordPress Themes via cPanel File Manager:


Alternatively, you'll use your net host cPanel to find the wp-content folder. below the file, manager click on – public_html look for the precise web site (if you've got many WordPress sites put in in the same server) and open the wp-content folder then navigate to themes folder to start renaming the themes one by one as shown in the image below.


WordPress Plugins Conflicts:


The next chance is that a WordPress plugin doesn't work properly with the active theme during custom Wordpress development, different plugins or the WordPress configurations.

A common situation may be a plugin with JavaScript conflict error that affects the way different plugins using the JavaScript library's work.

Disable WordPress Plugins via FTP Client – Filezilla:


Just like the step higher than of disabling WordPress themes, navigate to the wp-content folder and find the plugins folder. not like when you are disabling themes, disabling the plugins we are getting to rename the whole folder to plugins_old rather than one by one plugin. after you rename the folder, refresh the site to see if the interior server error is resolved.


If it's resolved, move and begin activating the plugins one by one to seek out out that plugin is causing the error.

Disable WordPress Plugins via cPanel:


You can additionally disable all the WordPress plugins through the cPanel by navigating to the public_html folder then go to the wp-content folder and rename the plugins folder to ‘plugins_old.’

After renaming the plugin folder you must refresh your website to see if the error is resolved. create a new plugin folder and add and activate the plugins one by one to spot the plugin that's inflicting the error.

If you don’t know how to disable plugin via cPanel, then there are a lot of companies available in the market which provides the top custom WordPress development services.


Increase the PHP Memory Limit:


Here we are going to extend our PHP memory limit to solve the error. There may be times when you exceed the PHP memory limit that causes this internal server error.

Make a php.ini File


Let’s assume you are doing not have the php.ini file on your server, to make one, easily make a blank document (use notepad) and name it php.ini. include to the file this code – memory_limit=64; as shown below:


Save the file and transfer it to the server root via FTP, refresh your web site and see if the solution works.

If it doesn't work, you'll be able to increase the memory by ever-changing the worth ‘64’ in the code above. Double the quantity 128, 256, refresh to examine if it works.

You may even have an existing php.ini file in your server root, merely open the file and edit it to double the quantity from 64 to 128 to examine if it resolves the error.

If this doesn't work strive once more with 256 to examine if it works.

Corrupted .htaccess:


The next solution will be a deal with a corrupted .htaccess file. This file is found in the root WordPress installation directory along with different vital WordPress files.

Easily right-click the file or rename it something like .htaccess_old.


Refresh your web site and if it works, move to your WordPress dashboard and click on Settings menu then Permalinks.

Under the Permalinks choices, you do not need to add anything however easily click Save Changes, and a new .htaccess is generated.


Web Host Server Side Problem – Last Resort:


Lastly, if none of those solutions work, you will have to be compelled to contact your internet host to clarify to them the error and what you have got tried and what choices are available.

They may tell you it's something they're working on or if it's a server-side issue.

You could even have outgrown your net hosting package as a result of your web site is so fashionable and you're exceeding the specifications that they need allotted your package. they'll advise you on what you would like to upgrade your net hosting package.

I hope these easy solutions are of profit to you and one of these solutions helped solve the interior server error.




Author

Author’s Bio

Sameer serves as a Digital Marketing Executive in the leading Wordpress Development Company named Techno Softwares and there he handles all works related to SEO, SMO, PPC, SME, Content Writing and E-mail Marketing Works.

  1. Linkedin :- https://www.linkedin.com/in/sameer-mishra-a49402194/

How to Use SMTP Mail Server to Send Emails in WordPress



Are you having hassle sending emails from your WordPress site? One simple thanks to solve this is often by sending WordPress emails using the Gmail SMTP server. during this article, we'll show you the way to send emails from your WordPress website using the Gmail SMTP server.

Why and when after you want Gmail SMTP Server for WordPress Emails


Your WordPress web site sends emails to inform you of recent user registration, lost password reset, automatic updates, and even notifications from your contact forms.

By default, WordPress uses the PHP mail to operate to transfer email notifications. However, this operate doesn't work as expected because of a variety of reasons.

Most WordPress hosting corporations prohibit usage of this operate to stop abuse and spam.

Spam filters on well-liked email service suppliers check incoming emails to watch if they're sent from authentic mail servers. Default WordPress emails fail this check and typically might not even build it to the spam folder.

SMTP (Simple Mail Transfer Protocol) is the business standard for sending emails. not like PHP mail function, SMTP uses correct authentication that will increase email deliverability.

Gmail provides SMTP service that you just will use to transmit emails from your WordPress website. If you simply need to send WordPress notification emails to yourself and few users on your website, then Gmail SMTP servers are the simplest choice.

However, if you're designing on sending newsletter emails using WordPress, then you must use a mass emailing service supplier, like MailGun or SendGrid.

Paid vs Free Gmail SMTP Service for WordPress


You can use your free Gmail account to transfer WordPress emails. However, for higher deliverability, we have a tendency to suggest using paid Google Apps for Work with Gmail.

With Google Apps for Work, you get your own skilled branded email address like (name@yoursite.com).

Google Apps need you to feature MX records to your domain name which implies that your emails can seem to be coming back from your own domain name boosting credibility and ensuring higher deliverability.

We use Google Apps for Work for WPBeginner and might honestly say it’s the simplest.

Upon activation, you would like to go to the Settings » WP Mail SMTP page to configure the plugin settings.

How to Send WP emails Using Gmail SMTP Server


If you made the choice to use Google Apps for Work, then you first have to be compelled to start your domain to work with Google Apps. we've a step by step tutorial on a way to set up an expert email address with Google Apps and Gmail.

Rest of the directions are the same whether you're using paid or free Gmail account.

The first thing you would like to do is install and activate the WP Mail SMTP plugin. For a lot of details, see our step by step guide a way to install a WordPress plugin.

Upon activation, you would like to go to the Settings » WP Mail SMTP page to configure the plugin settings.


First you wish to create sure that you just use your Gmail email address within the ‘From Email’ field. Next, you need to produce the sender name.

WP Mail SMTP plugin offers two ways to attach your WordPress web site to the Gmail servers.

The first technique uses OAuth Authentication. this can be a safer technique to send emails using Gmail servers.

The second technique is by coming into Gmail SMTP settings manually. This technique isn't suggested because it's less secure.

That being said, let’s established WordPress to use Gmail SMTP for sending emails.

If don’t understand how to Send WordPress mails Using Gmail SMTP Server then lot of companies available in the market those provide Wordpress Development Services.




Strategic 1: setting up Gmail to Send WordPress Emails using OAuth Protocol


This technique is suggested for all users. it's safer and once you set it up, you’ll ne'er need to do this once more.

You need to begin by choosing Gmail as your mailer and set the comeback path to be similar to the sender.


Next, you may see the choice to enter your consumer ID, Consumer Secret, and a universal resource locator(URL) in the ‘authorize redirect URI’ field.

Let’s established these fields.

Creating AN Application and Generate API Keys for Gmail


Visit the Google Developers Console web site and build a brand new project.


If you don’t see the blue button to make a project, then you'll be able to additionally click on choose a project drop-down and build a brand new project.

You’ll be asked to produce a name for your project. provides it an unforgettable name, so you'll be able to simply recognize it within the future.


After that, click on the create button to continue.

Developer console can currently create your project and take you to its dashboard. Google provides developers access to several of their Apis and services. you wish to enable the Apis that you just are going to be needing for this project.


Click on modify APIs and services button to continue..

It will bring you to the APIs library page. Next, you would like to kind Gmail in the search box to quickly notice the Gmail API and click on to pick out it.


You will currently see an outline of the API and what it will do. easily click on the ‘Enable’ button to continue.


Now that your API is enabled, the next step is to make credentials that you just will use in your WP Mail SMTP plugin settings.

Click on the produce credentials button to continue.


On the next screen, you may have to be compelled to choose ‘Web browser JavaScript’ in ‘Where you’ll be calling the API from’ field. then click on the 'User Data' choice.


To proceed further, click on the ‘What credentials do I need?’ button.

You will currently be asked to supply a name for your OAuth consumer name. you'll enter 'WP Mail SMTP' here.


Under the JavaScript origins field, you wish to feature your website’s domain name. Next, you need to copy and paste the approved redirect universal resource locator(URL) from WP Mail SMTP plugin settings.

After that click on the ‘Create consumer ID’ button to continue.

Next, you wish to enter a name for the OAuth consent screen. you'll place the plugin’s name here.


After coming into the main points, click on the continue button and also the developer console can show your consumer ID. you'll copy and paste this in the WP Mail SMTP plugin’s settings page. However, you may still have to be compelled to add your consumer secret key.

Go ahead and click on the Done button to move on.

You will currently be taken to your project’s credentials page. you'll see your recently created credentials listed there. you wish to click on the edit icon next to your credentials to continue.

This will bring you to the edit credentials page wherever you may be ready to see your consumer secret key. you would like to repeat and paste the key in your plugin’s settings page.

Return back to plugin’s settings page in your WordPress admin space. currently that you simply have each consumer ID and consumer secret keys, you need to click on the save settings button to continue.


The plugin can currently store your settings and reload the page. After that, you would like to scroll right down to the bottom of the settings page and click on on the ‘Allow plugin to send emails using your Google account’ button.

This will take you to your account on Google, and you may be asked to provide the web site permission to send emails on your behalf.

Click on the enable button to provide permissions.

After that, you may be redirected back to your web site where you may see successful message.

Strategic 2: Setting up Gmail SMTP as SMTP Sender


This technique permits you to manually connect with Gmail’s SMTP servers to send your WordPress emails.

First, you should go to the Settings » WP Mail SMTP page to configure the plugin settings.

You need to begin by providing the Gmail address you wish to use within the email form field and your name in the name field.

Next, you wish to pick out ‘Other SMTP’ as your mailer and check the box next to the comeback path.

After that, scroll right down to the other SMTP section to configure additional settings.


Here is that the actual configuration you would like to feature within the plugin settings:

  • SMTP Host: smtp.gmail.com
  • SMTP Port: 465
  • Encryption: Use SSL encryption
  • Authentication: turn on authentication
  • Username: Your complete Gmail address, e.g.
    sameer.m.technosoftwares@yourdomain.com or
    sameer.m.technosoftwares@gmail.com
  • Password: password of your Gmail account

Once you're done, click on the save changes button to store your settings. That’s all, you have got with success set up WP Mail SMTP to use Gmail SMTP servers.

Testing Your WP Mail.SMTP Settings


WP Mail SMTP plugin permits you to check your email settings, so you'll check that everything is working properly.

You should visit the Settings » WP Mail SMTP page and click on the ‘Email Test’ tab. simply offer AN email address that you simply will access within the send to field and click on the send email button.


You will see a hit message. you'll currently check your inbox to check a message with the topic line ‘WP Mail SMTP: check Email to…’.

That’s all, you have got with success created your WordPress web site to send emails using Gmail SMTP servers.

Troubleshooting Gmail SMTP Not working problems


We have seen users encounter few problems once using Gmail SMTP with bound shared hosting configurations.

Take the following steps to repair the Gmail SMTP issue:
  1. Login to your cPanel account and build an email account that matches your Google apps email address. This might seem strange as a result of you’re not using your server for emails. This step primarily tricks your server into basic cognitive process that you’re sending the e-mail through the server.
  2. In your cPanel account, move to the Mx Records and change the Mx routing from automatic to remote. it'd be a bit tough to search out since every host currently has a custom cPanel interface. you wish to seem for a little link next to Mx that claims Email Routing: Remote Mail exchanger.
  3. After that log into your WordPress web site and send a check email.

We hope this tutorial helps you to how WordPress uses the PHP Mail function to send its emails. However, it's better to use SMTP because it handles sending messages better and you'll be able to also.. function, a Gmail/G Suite account, Mailgun, SendGrid or different SMTP servers.

If you don’t know how to personalize or customize a WordPress theme according to your needs, then there are a lot of companies available in the market which provides the top custom WordPress development services.



Author

Author’s Bio

Yashraj serves as a Digital Marketing Executive in the leading Wordpress development company named Techno Softwares and there he handles all works related to SEO, SMO, PPC, SME, Content Writing and E-mail Marketing Works. He use to publish his articles on Medium.com.

  1. Instagram:- https://www.instagram.com/yashrajss121/
  2. LinkedIn:- https://in.linkedin.com/in/yashrajsingh7876
  3. Twitter:- https://twitter.com/yashraj7876/

Thursday, 10 October 2019

How to Implement Login using Facebook Account in PHP



This is one more post on How to make Social Login in PHP. In this post, we will use Facebook account login allow to user for get access into our website. Here you can find process for login with Facebook PHP SDK library. In this tutorial, we have use latest Facebook API SDK library for login with PHP script.

In most of website, you can generally find registration form for sign up for get access into website, but most of the user is not interested in filling large website registration form. At this time if you have allow user to login or register with Facebook login, then user has not required to filling large registration form and they can easily get access into website by login using Facebook account. In this blog, we will learn you how to implement login with Facebook account in your PHP website.

Here we have use Facebook PHP SDK library that allows to access Facebook API from your PHP web application. By using this library you can simply integrate the PHP Login with Facebook Account using Facebook SDK library. Here you can find process for how to make User login and registration system with Facebook using PHP and display user profile data on web page.




Now we have get started with the latest version of Facebook SDK v5.x and your system must required following configuration.

  • PHP version must be greater than 5.4.
  • mbstring extension must be enable in your server.

Create Facebook APP


For get access Facebook API, first you need to create Facebook app and then get App ID and App Secret which you can use at the time of calling Facebook API. Below you can find step by step process for create Facebook app in Facebook developers dashboard.

1. First go to https://developers.facebook.com/ facebook developers page and login with your Facebook Account.

2. After login into Facebook account, now click on My apps menu and in this click on Create App link.




3. After click on Create App link, then modal has pop up on web page, here you have to define App Display Name details and click on Create App ID button.




4. Now navigate to Setting » Basic link.




5. Here you have to specify App Domains, Privacy Policy URL, Terms of Service URL and select Category. Lastly, you have to click on Save Changes button.




6. Now you have to navigate to Add a Product page by click on plus button. So, modal will pop up and here you have to select Website.




7. After select Website option, then Website field has been appear on web page, and here you have to define your app Site URL.




8. Now you have to add product, so go to Dashboard link and on you have to Set up Facebook Login product.

9. Once you have Set up Facebook Login product, then new web page has been load, here you have to define Valid OAuth Redirect URIs and click on Save Changes button.




10. You have change your status from In Development mode to Live mode, for this you have to click on Off button, after click on Off button, then modal will pop up and here you have to select Category and click on Switch Mode button. After click on Switch Mode button, your App will be Live this is required for get profile data from Facebook API.



Download Facebook SDK for PHP


After this we want to download Facebook SDK for PHP library. For this we have to open Command Prompt editor. In this first you have to go to directory in which you want to download Facebook SDK for PHP. After this you have to run Composer command, this is because we have use Composer dependecy manager for download Facebook SDK for PHP. After this you have to run following command.


composer require facebook/graph-sdk


This command will download Facebook SDK library for PHP in define directory.

config.php


In this file first we need to add autoload.php file of Facebook SDK library for PHP using require_once statement.

After this, we have to check, session variable started or not by using PHP session_id() function.

Now we have to called Facebook API, here we have to define app_id and app_secret key which we have to get at the time of create Facebook App. Here we have to define default_graph_version also.


<?php

require_once 'vendor/autoload.php';

if (!session_id())
{
    session_start();
}

// Call Facebook API

$facebook = new \Facebook\Facebook([
  'app_id'      => '921130358246916',
  'app_secret'     => '8d382dc63a190925664594ef090b8a78',
  'default_graph_version'  => 'v2.10'
]);

?>


index.php


In this file first we need to add config.php file by using include statement.

After this we want to get redirect login helper, for this here we have use getRedirectLoginHelper() method.

Now we want to check any $_GET['code'] variable value has been received or not, if received that means user has login using Facebook account and display profile data on web page, otherwise display link for Login using Facebook account.

Suppose it has received $_GET['code'] variable value, then we want to check access token has been store in $_SESSION variable or not if it is already store in $_SESSION variable, then that value has been store in local variable.

But suppose access token is not get from $_SESSION variable, then we need to get by using getAccessToken() method and store in local variable and then after store in $_SESSION variable.

After getting access token now we want to set the default access token to use with request by using setDefaultAccessToken() method.

Now we have proceed for get profile data, for this here we have use get() method and under this method we have to define profile fields like name, email etc and in second argument we have to define access token value.

Lastly, for get user profile data, here we have use getGraphUser(), this method will creating a graph user collection.

This way we can get data from Facebook API and store in $_SESSION variable.

For create link for login using Facebook account, for this here we have use getLoginUrl() method, this method will send the user in order to login to Facebook. In this method you have to define redirect url and permission array.

So, below you can source code for get login with Facebook account using PHP and display profile data on web page.


<?php

//index.php

include('config.php');

$facebook_output = '';

$facebook_helper = $facebook->getRedirectLoginHelper();

if(isset($_GET['code']))
{
 if(isset($_SESSION['access_token']))
 {
  $access_token = $_SESSION['access_token'];
 }
 else
 {
  $access_token = $facebook_helper->getAccessToken();

  $_SESSION['access_token'] = $access_token;

  $facebook->setDefaultAccessToken($_SESSION['access_token']);
 }

 $_SESSION['user_id'] = '';
 $_SESSION['user_name'] = '';
 $_SESSION['user_email_address'] = '';
 $_SESSION['user_image'] = '';

 $graph_response = $facebook->get("/me?fields=name,email", $access_token);

 $facebook_user_info = $graph_response->getGraphUser();

 if(!empty($facebook_user_info['id']))
 {
  $_SESSION['user_image'] = 'http://graph.facebook.com/'.$facebook_user_info['id'].'/picture';
 }

 if(!empty($facebook_user_info['name']))
 {
  $_SESSION['user_name'] = $facebook_user_info['name'];
 }

 if(!empty($facebook_user_info['email']))
 {
  $_SESSION['user_email_address'] = $facebook_user_info['email'];
 }
 
}
else
{
 // Get login url
    $facebook_permissions = ['email']; // Optional permissions

    $facebook_login_url = $facebook_helper->getLoginUrl('https://greenhouses-pro.co.uk/demo/', $facebook_permissions);
    
    // Render Facebook login button
    $facebook_login_url = '<div align="center"><a href="'.$facebook_login_url.'"><img src="php-login-with-facebook.gif" /></a></div>';
}



?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>PHP Login using Google Account</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">PHP Login using Google Account</h2>
   <br />
   <div class="panel panel-default">
    <?php 
    if(isset($facebook_login_url))
    {
     echo $facebook_login_url;
    }
    else
    {
     echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
     echo '<img src="'.$_SESSION["user_image"].'" class="img-responsive img-circle img-thumbnail" />';
     echo '<h3><b>Name :</b> '.$_SESSION['user_name'].'</h3>';
     echo '<h3><b>Email :</b> '.$_SESSION['user_email_address'].'</h3>';
     echo '<h3><a href="logout.php">Logout</h3></div>';
    }
    ?>
   </div>
  </div>
 </body>
</html>


logout.php



<?php

//logout.php

session_destroy();

header('location:index.php');

?>


So, from this post you can learn how to allow user to login using Facebook account in PHP website, We hope you have learn login with Facebook in PHP web application from this post.

Friday, 27 September 2019

How to make Login with Google Account using PHP



Now a days in the world of internet, as we know social media is an very import part of any web based application. So if your web application has provide feature like login with social media, then it will be gaining more new users to your web application. So, in this post we have share tutorial on how to login or sign in or register with Google Account in your PHP web application. Here we will make system in which user can login with their Google account into your website.

For login with Google Account using PHP, Google has provide Google OAuth API, which is very easy and helpful to you for implement login using Google account into your Website. Google Login API has provide rights to user to login into the website by using their Google account credential without register on that particular website. By using this feature, your website will gain more subscriber, this is because in current days most of all users have a Google Account, so they can login with their Google Account without sign in on your website.

In this tutorial, we will use Google OAuth Login API, this API give permission to users to login with their existing Google accounts to your website. Below you can find how to integrate Google Login API in your PHP website and you can also find the process how to get API key and how to integrate Google Client Library in your existing PHP library for Login.





Get Google API Credential


First we need to get Google API keys, for this first you have Google Account. So, login into your Google Account and follow below step.

1 - Go to https://console.developers.google.com/ this link.
2 - After this click on Create New Project link for create new project.


3 - Enter Project Name and click on Create button.

4 - Once you have create new project then you can see your project list on web page.

5 -After this click on Google API logo for go to home page.





6 - Once you have redirect to home page then select project from the project select box.


7 - After click on project select box, then one modal will popup and under this you can find list of project, so select your project.


8 - Now from left menu, you have to click on OAuth consent screen.
9 - Once you have click on OAuth consent screen, then one page will load, here you have to define application name and after this click on save button.


10 - When you have click on save button, then after page will redirect another page, and here you have to click on Create credential button, so one drop down menu will appear and from this you have to select OAuth client ID.


11 - After click on OAuth client ID menu then you have redirect to another page, and here you can find different Application type.


12 - From different Application type option, you have to select Web application. Once you have select Web application option, then one form will appear on web page. Here you have to define Name and you have also define Authorized redirect URIs field and lastly click on Create button.


13 - Once you have click on create button, then you can get your Client ID and your client secret key. You have to copy both key for future use for implement Login using Google account using PHP.


Download Google API Client Library for PHP


After getting Google API key, now we need to download Google API Client Library for PHP. For this we have to go command prompt and first type composer command, after this we need to run following command.


composer require google/apiclient:"^2.0"


This command will download Google API Client Library for PHP in your define directory. Now we have proceed for PHP code for how to use Google API Client Library for login using Google account with PHP.

config.php



<?php

//config.php

//Include Google Client Library for PHP autoload file
require_once 'vendor/autoload.php';

//Make object of Google API Client for call Google API
$google_client = new Google_Client();

//Set the OAuth 2.0 Client ID
$google_client->setClientId('1034286712318-kv0gapfqro1aijq84ed72r4aqqs8nan8.apps.googleusercontent.com');

//Set the OAuth 2.0 Client Secret key
$google_client->setClientSecret('Dzq5Xd3olizoZkKjk_SJCWQ1');

//Set the OAuth 2.0 Redirect URI
$google_client->setRedirectUri('http://localhost/tutorial/php-login-using-google-demo/index.php');

//
$google_client->addScope('email');

$google_client->addScope('profile');

//start session on web page
session_start();

?>


index.php



<?php

//index.php

//Include Configuration File
include('config.php');

$login_button = '';

//This $_GET["code"] variable value received after user has login into their Google Account redirct to PHP script then this variable value has been received
if(isset($_GET["code"]))
{
 //It will Attempt to exchange a code for an valid authentication token.
 $token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);

 //This condition will check there is any error occur during geting authentication token. If there is no any error occur then it will execute if block of code/
 if(!isset($token['error']))
 {
  //Set the access token used for requests
  $google_client->setAccessToken($token['access_token']);

  //Store "access_token" value in $_SESSION variable for future use.
  $_SESSION['access_token'] = $token['access_token'];

  //Create Object of Google Service OAuth 2 class
  $google_service = new Google_Service_Oauth2($google_client);

  //Get user profile data from google
  $data = $google_service->userinfo->get();

  //Below you can find Get profile data and store into $_SESSION variable
  if(!empty($data['given_name']))
  {
   $_SESSION['user_first_name'] = $data['given_name'];
  }

  if(!empty($data['family_name']))
  {
   $_SESSION['user_last_name'] = $data['family_name'];
  }

  if(!empty($data['email']))
  {
   $_SESSION['user_email_address'] = $data['email'];
  }

  if(!empty($data['gender']))
  {
   $_SESSION['user_gender'] = $data['gender'];
  }

  if(!empty($data['picture']))
  {
   $_SESSION['user_image'] = $data['picture'];
  }
 }
}

//This is for check user has login into system by using Google account, if User not login into system then it will execute if block of code and make code for display Login link for Login using Google account.
if(!isset($_SESSION['access_token']))
{
 //Create a URL to obtain user authorization
 $login_button = '<a href="'.$google_client->createAuthUrl().'"><img src="sign-in-with-google.png" /></a>';
}

?>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>PHP Login using Google Account</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
  
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">PHP Login using Google Account</h2>
   <br />
   <div class="panel panel-default">
   <?php
   if($login_button == '')
   {
    echo '<div class="panel-heading">Welcome User</div><div class="panel-body">';
    echo '<img src="'.$_SESSION["user_image"].'" class="img-responsive img-circle img-thumbnail" />';
    echo '<h3><b>Name :</b> '.$_SESSION['user_first_name'].' '.$_SESSION['user_last_name'].'</h3>';
    echo '<h3><b>Email :</b> '.$_SESSION['user_email_address'].'</h3>';
    echo '<h3><a href="logout.php">Logout</h3></div>';
   }
   else
   {
    echo '<div align="center">'.$login_button . '</div>';
   }
   ?>
   </div>
  </div>
 </body>
</html>


logout.php



<?php

//logout.php

include('config.php');

//Reset OAuth access token
$google_client->revokeToken();

//Destroy entire session data.
session_destroy();

//redirect page to index.php
header('location:index.php');

?>


So, this is complete process for How to use Google API Client library for PHP Login by using Google account.