PHP Create,Access,and Destroy Cookies Tutorial

create,access,and destroy cookies in php

Hi Guys,

In this blog,I will explain you how to create,access,and destroy cookies in php a cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.They are typically used to keeping track of information such as a username that the site can retrieve to personalize the page when the utilizer visits the website next time.A cookie can only be read from the domain that it has been issued from.Cookies are conventionally set in an HTTP header but JavaScript can withal set a cookie directly on a browser.

Tip:Each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within the request.
Setting a Cookie in PHP

The setcookie() function is utilized to set a cookie in PHP. Ascertain you call the setcookie() function before any output engendered by your script otherwise cookie will not set. The basic syntax of this function can be given with:

Syntax:
setcookie(name, value, expire, path, domain, secure);

The parameters of the setcookie() function have the following meanings:

  1. Name:It is used to set the name of the cookie.
  2. Value:It is utilized to set the value of the cookie.
  3. Expire:It is utilized to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
  4. Path:It is utilized to designate the path on the server for which the cookie will be available.
  5. Domain: It is used to specify the domain for which the cookie is available.
  6. Security:It is utilized to denote that the cookie should be sent only if a secure HTTPS connection exists.
Tip:

If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the session i.e. when the browser closes.

Creating Cookies:

Here's an example that utilizes setcookie() function to engender a cookie named username and assign the value value Dharmik to it. It additionally specify that the cookie will expire after 30 days (30 days * 24 hours * 60 min * 60 sec).

<?php  

  // Setting a cookie
  setcookie("username", "Dharmik", time()+30*24*60*60);

?>
Note:

Only the designation argument in the setcookie() function is obligatory.To skip an argument,the argument can be replaced by a vacuous string(“”).

Warning:

Don't store sensitive data in cookies since it could potentially be manipulated by the maleficent utilizer. To store the sensitive data securely use sessions instead.

Accessing Cookies Values

The PHP $_COOKIE superglobal variable is utilized to retrieve a cookie value. It typically an associative array that contains a list of all the cookies values sent by the browser in the current request, keyed by cookie name. The individual cookie value can be accessed utilizing standard array notation, for example to display the username cookie set in the precedent example, you could utilize the following code.

Example
<?php

  // Accessing an individual cookie value
  echo $_COOKIE["username"];

?>
Output
Dharmik

It's a good practice to check whether a cookie is set or not before accessing its value. To do this you can utilize the PHP isset() function, like this:

Example
<?php

  // Verifying whether a cookie is set or not
  if(isset($_COOKIE["username"])){
      echo "Hi " . $_COOKIE["username"];
  } else{
      echo "Welcome MyWebtuts.com";
  }

?>

You can utilize the print_r() function like print_r($_COOKIE); to optically discern the structure of this $_COOKIE associative array, like you with other arrays.

Removing Cookies

You can delete a cookie by calling the same setcookie() function with the cookie name and any value (such as a empty string) however this time you require the set the expiration date in the past, as shown in the example below:

Example
<?php

// Deleting a cookie
setcookie("username", "", time()-3600);

?>
Note:

The same path, domain, and other arguments should be passed that were used to engender the cookie in order to ascertain that the correct cookie is deleted.

It will help you..

Laravel Validation email Tutorial

validation email in laravel

Hi Dev,

Today, I will learn you to create validation email in laravel.we will show example of laravel validation email.The field under validation must be formatted as an e-mail address

Here, I will give you full example for simply email validation in laravel bellow.

solution
$request->validate([
  'email' => 'required|email',
]);
Route : routes/web.php
Route::get('form/create','FromController@index');
Route::post('form/store','FromController@store')->name('form.store');
Controller : app/Http/Controllers/BlogController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FromController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
        ]);
        
        dd('done');
    }
}
View : resources/views/form.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                 Laravel Validation email Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
                @if (count($errors) > 0)
                      <div class="row">
                          <div class="col-md-12">
                              <div class="alert alert-danger alert-dismissible">
                                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                                  @foreach($errors->all() as $error)
                                  {{ $error }} <br>
                                  @endforeach      
                              </div>
                          </div>
                      </div>
                    @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Email:</label>
                      <input name="email" type="text" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...

Laravel 8 ConsoleTvs Charts Tutorial

how to use consoletvs charts in laravel 8
Hi Guys, Today,I will learn you how to use consoletvs charts in laravel 8. If you need to add some graphs to your views, maybe you have work with some js library to add cool graphics but even with a good library like ChartJS implementing this is not so easy. Step 1: Install Laravel 8 Application we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2 :Installing consoletvs Package Now In this step, install consoletvs/charts:6 package in laravel 8 app via following command.
composer require consoletvs/charts:6
If you are working with Laravel 5.5 or higher thats all you need to install the package thanks by autodiscover feature. If you work with Laravel lower than 5.5 you will need to register a service provider, add this line into the config/app.php file in the providers section:
ConsoleTVs\Charts\ChartsServiceProvider::class,
And to publish the configuration in terminal with the command:
php artisan vendor:publish --tag=charts_config
Now you have the package installation done! Step 3: Use the package in this step, We are going to use artisan cli to create a chart class.
php artisan make:chart UserChart
Now in app directory we can see a folder named charts and there is our new class UserChart.php. Step 4: Create Controller I will explain with an easy example but you can add as many complexity as you want, we are going to create a controller of type resource to display user chart:
php artisan make:controller UserChartController -r
Now you can edit the file in app/Http/Controllers/UserChartController.php and only hold the index method all other rest full methods can be deleted, and you will have something like this:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

}
To make it more easy I will create a fake data but you can use eloquent o queryBuilder to create queries as you need, I will import the new chart class created before to the controller, and start to create a chart with Laravel chart api fluid syntax:
<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13]);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}
Now we need a view to show the data in the last code snippet the index method returns a view for users charts, so I will create a file in resources/views/ named users.blade.php, with next content:
@extends('layouts.app')

@section('content')
<h1>Sales Graphs</h1>

<div style="width: 50%">
    {!! $salesChart->container() !!}
</div>
@endsection
Now we pass the chart script to the view file we only need to add the chart css and js library files, to keep it simple we are going to use the layout app blade file, it is located in resources/views/layout/app.blade.php, here we are going to add in header section the next line at the very bottom:
<head>
    <meta charset="utf-8">
    ...
    {{-- ChartScript --}}
    @if($usersChart)
    {!! $usersChart->script() !!}
    @endif
</head>
To add JS library file we are going to the bottom to the file app.blade.php, before the html close tag and add the scripts:
@extends('layouts.app')

@section('content')
<h1>Users Graphs</h1>

<div style="width: 50%">
    {!! $usersChart->container() !!}
</div>
@endsection
Finally we only need a route to access to the graphic view, in routes/web.php file you can add a route with get method to access to the usersChartController class in method index() in the example I set a route to 'sales':
<?php
use App\Http\Controllers\UserChartController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

....

Route::get('users', 'UserChartController@index');
Well it is simple but, maybe you want to customize it a little bit more, you can customize the charts by two ways, you can customize the "dataset" and the chart as itself, to start we are going to customize the "dataset":
<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13])
            ->color("rgb(255, 99, 132)")
            ->backgroundcolor("rgb(255, 99, 132)");
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}
The method "color" set the border color in the case of a "line" or "area" charts it sets the line color, and as param requires a string with the rgb or rgba color The method "backgroundcolor" set the area color, the color to fill, and as param requires a string with the rgb or rgba color
"fill" method requires a boolean and it paint the area or not if it is set as false, by default a chart is filled.
"linetension" method make less curved a line and it requires a float from 0.0 to 1.0
"dashed" method makes the line a dashed line and it requires an array.

Customize the chart

To customize the chart we can use some methods: ->"minimalist" method requires a boolean and it removes the grid background and the legend of the chart ->"displaylegend" methods requires a boolean and it is true by default, to hide the legend set false as param. ->"displayaxes" method requieres a boolean and by default is true it, paint the background grid of the chart, to hide it just set false as the param. ->"barWidth" this method does not do anything in line and area charts, it requires a double.
<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $usersChart = new UserChart;
        $usersChart->title('Users by Months', 30, "rgb(255, 99, 132)", true, 'Helvetica Neue');
        $usersChart->barwidth(0.0);
        $usersChart->displaylegend(false);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'line', [10, 25, 13])
            ->color("rgb(255, 99, 132)")
            ->backgroundcolor("rgb(255, 99, 132)")
            ->fill(false)
            ->linetension(0.1)
            ->dashed([5]);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

Doughnutexample:

<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $borderColors = [
            "rgba(255, 99, 132, 1.0)",
            "rgba(22,160,133, 1.0)",
            "rgba(255, 205, 86, 1.0)",
            "rgba(51,105,232, 1.0)",
            "rgba(244,67,54, 1.0)",
            "rgba(34,198,246, 1.0)",
            "rgba(153, 102, 255, 1.0)",
            "rgba(255, 159, 64, 1.0)",
            "rgba(233,30,99, 1.0)",
            "rgba(205,220,57, 1.0)"
        ];
        $fillColors = [
            "rgba(255, 99, 132, 0.2)",
            "rgba(22,160,133, 0.2)",
            "rgba(255, 205, 86, 0.2)",
            "rgba(51,105,232, 0.2)",
            "rgba(244,67,54, 0.2)",
            "rgba(34,198,246, 0.2)",
            "rgba(153, 102, 255, 0.2)",
            "rgba(255, 159, 64, 0.2)",
            "rgba(233,30,99, 0.2)",
            "rgba(205,220,57, 0.2)"

        ];
        $usersChart = new UserChart;
        $usersChart->minimalist(true);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'doughnut', [10, 25, 13])
            ->color($borderColors)
            ->backgroundcolor($fillColors);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}

Bar example

With a little effort and the default bootstrap from Laravel installation: UserChartController to generate the chart
<?php

namespace App\Http\Controllers;

use App\Charts\UserChart;
use Illuminate\Http\Request;

class UserChartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $borderColors = [
            "rgba(255, 99, 132, 1.0)",
            "rgba(22,160,133, 1.0)",
            "rgba(255, 205, 86, 1.0)",
            "rgba(51,105,232, 1.0)",
            "rgba(244,67,54, 1.0)",
            "rgba(34,198,246, 1.0)",
            "rgba(153, 102, 255, 1.0)",
            "rgba(255, 159, 64, 1.0)",
            "rgba(233,30,99, 1.0)",
            "rgba(205,220,57, 1.0)"
        ];
        $fillColors = [
            "rgba(255, 99, 132, 0.2)",
            "rgba(22,160,133, 0.2)",
            "rgba(255, 205, 86, 0.2)",
            "rgba(51,105,232, 0.2)",
            "rgba(244,67,54, 0.2)",
            "rgba(34,198,246, 0.2)",
            "rgba(153, 102, 255, 0.2)",
            "rgba(255, 159, 64, 0.2)",
            "rgba(233,30,99, 0.2)",
            "rgba(205,220,57, 0.2)"

        ];
        $usersChart = new UserChart;
        $usersChart->minimalist(true);
        $usersChart->labels(['Jan', 'Feb', 'Mar']);
        $usersChart->dataset('Users by trimester', 'bar', [10, 25, 13])
            ->color($borderColors)
            ->backgroundcolor($fillColors);
        return view('users', [ 'usersChart' => $usersChart ] );
    }

}
blade view with some bootstrap for styling
@extends('layouts.app')

@section('content')
<div class="container">
    <h1>Users Graphs</h1>
    <div class="row">
        <div class="col-6">
            <div class="card rounded">
                <div class="card-body py-3 px-3">
                    {!! $usersChart->container() !!}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
It will help you...

Laravel 8 Resize Image Before Upload Example Tutorial

laravel 8 generate thumbnail image

Hi Guys,

Today, I will learn you how to resize image before upload in laravel 8. we will show example of resize image before upload in laravel 8.if you want to see example of laravel 8 generate thumbnail image then you are a right place. we will help you to give example of laravel 8 resize image before upload.I will explain step by step tutorial laravel 8 resize image.

We will give you simple example of laravel 8 image intervention example. you will do the following things for resize and upload image in laravel 8.

we will use intervention/image package for resize or resize image in laravel. intervention provide a resize function that will take a three parameters. three parameters are width, height and callback function. callback function is a optional.

Here, I will give you full example for simply resize image before upload using laravel as bellow.

Step 1: Install Laravel 8

Here In this step, If you haven't laravel 8 application setup then we have to get fresh laravel 8 application. So run bellow command and get clean fresh laravel 8 application.

composer create-project --prefer-dist laravel/laravel blog
Step 2: Install Intervention Image Package

n this step,I will install intervention/image for resize image. this package through we can generate thumbnail image for our project. so first fire bellow command in your cmd or terminal.

composer require intervention/image

Now we need to add provider path and alias path in config/app.php file so open that file and add bellow code.

config/app.php
return [
    ......
    $provides => [
        ......,
        ......,
        Intervention\Image\ImageServiceProvider::class
    ],
    $aliases => [
        ......,
        .....,
        'Image' => Intervention\Image\Facades\Image::class
    ]
]
Step 3: Create Routes

In this step,we will add routes and controller file so first add bellow route in your routes.php file.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageResizeController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('resizeImage', [ImageResizeController::class, 'resizeImage']);
Route::post('resizeImagePost', [ImageResizeController::class, 'resizeImagePost'])->name('resizeImagePost');
Step 4: Create Controller File

In this step,Now require to create new ImageResizeController for image uploading and resizeing image so first run bellow command.

php artisan make:controller ImageResizeController

After this command you can find ImageResizeController.php file in your app/Http/Controllers directory. open ImageResizeController.php file and put bellow code in that file.

app/Http/Controllers/ImageResizeController.php
<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Http\Requests;
use Image;
  
class ImageResizeController extends Controller
{
  
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function resizeImage()
    {
        return view('resizeImage');
    }
  
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function resizeImagePost(Request $request)
    {
        $this->validate($request, [
            'title' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
  
        $image = $request->file('image');
        $input['imagename'] = time().'.'.$image->extension();
     
        $destinationPath = public_path('/thumbnail');
        $img = Image::make($image->path());
        $img->resize(100, 100, function ($constraint) {
            $constraint->aspectRatio();
        })->save($destinationPath.'/'.$input['imagename']);
   
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $input['imagename']);
   
        return back()
            ->with('success','Image Upload successful')
            ->with('imageName',$input['imagename']);
    }
   
}
Step 5: View File and Create Upload directory

In this last step we will create resizeImage.blade.php file for photo upload form and manage error message and also success message. So first create resizeImage.blade.php file and put bellow code:

resources/views/resizeImage.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Resize Image Tutorial</title>
    <link rel="stylesheet" href="https://www.nicesnippets.com/adminTheme/bower_components/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
  
<div class="container">
    <h1>Laravel Resize Image Tutorial</h1>
    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
         
    @if ($message = Session::get('success'))
    <div class="alert alert-success alert-block">
        <button type="button" class="close" data-dismiss="alert">×</button>    
        <strong>{{ $message }}</strong>
    </div>
    <div class="row">
        <div class="col-md-4">
            <strong>Original Image:</strong>
            <br/>
            <img src="/images/{{ Session::get('imageName') }}" />
        </div>
        <div class="col-md-4">
            <strong>Thumbnail Image:</strong>
            <br/>
            <img src="/thumbnail/{{ Session::get('imageName') }}" />
        </div>
    </div>
    @endif
         
    <form action="{{ route('resizeImagePost') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div class="row">
            <div class="col-md-4">
                <br/>
                <input type="text" name="title" class="form-control" placeholder="Add Title">
            </div>
            <div class="col-md-12">
                <br/>
                <input type="file" name="image" class="image">
            </div>
            <div class="col-md-12">
                <br/>
                <button type="submit" class="btn btn-success">Upload Image</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>
Now at last create two directory in your public folder (1)images and (2)thumbnail and please give permission to that folder and check....at last create two directory in your public folder (1)images and (2)thumbnail and please give permission to that folder and check.... It will help you...