Friday, February 26, 2016

Delete a file in Laravel 5.1

Delete file in Laravel 5.1:

Today we will discuss how to delete a file in Laravel 5.1

You know you could use PHP's unlink() method, but want to do it the Laravel way then use the File::delete() method.

<?php

namespace App\Http\Controllers;

use File;

class TestController extends Controller
{

 public function deleteFile()
 {
  // Delete a single file
  File::delete($filename);

  // Delete multiple files
  File::delete($file1, $file2, $file3);

  // Delete an array of files
  $files = array($file1, $file2);
  File::delete($files);
 }

}
?>


Errors are quietly ignored.

If there's a problem deleting the file, any error is silently ignored. If it's important that a file was deleted, check it's existence after deleting it with File::exists().

Thanks.

Friday, February 19, 2016

How to compress image in php

Compress image in php:

For compressing an image in php we have to use this code for this:


<?php
    function compress($source, $destination, $quality) {
        $info = getimagesize($source);
        if ($info['mime'] == 'image/jpeg')
            $image = imagecreatefromjpeg($source);
        elseif ($info['mime'] == 'image/gif')
            $image = imagecreatefromgif($source);
        elseif ($info['mime'] == 'image/png')
            $image = imagecreatefrompng($source);
        $res=imagejpeg($image, $destination, $quality);
        return $res;
    }
   compress('image.jpg','img/image.jpg',80);
?>



Here are the $source is the path of image and $destination is the path where we have to save the image after editing.

Thanks

Friday, February 12, 2016

How to generate a Certificate Signing Request (CSR) - Apache 2.x

Generate Certificate Signing Request in Apache:

Follow these instructions to generate a certificate signing request (CSR) for your Apache Web server. When you have completed generating your CSR, cut/copy and paste it into the CSR field on the SSL certificate-request page.
To Generate a Certificate Signing Request for Apache 2.x
1. Log in to your server's terminal (SSH).
    At the prompt, type the following command:


    openssl req -new -newkey rsa:2048 -nodes -keyout yourdomain.key -out yourdomain.csr
    Replace yourdomain with the domain name you're securing. For example, if your domain name is       coolexample.com, you would type coolexample.key and coolexample.csr.
   
2. Enter the requested information:
     2.1.  Common Name: The fully-qualified domain name, or URL, you're securing.
        If you are requesting a Wildcard certificate, add an asterisk (*) to the left of the common name where you want the wildcard, for example *.coolexample.com.
     2.2.  Organization: The legally-registered name for your business. If you are enrolling as an individual, enter the certificate requestor's name.
     2.3.  Organization Unit: If applicable, enter the DBA (doing business as) name.
     2.4.  City or Locality: Name of the city where your organization is registered/located. Do not abbreviate.
     2.5  State or Province: Name of the state or province where your organization is located. Do not abbreviate.
     2.6. Country: The two-letter International Organization for Standardization (ISO) format country code for where your organization is legally registered.
        If you do not want to enter a password for this SSL, you can leave the Passphrase field blank. However, please understand there might be additional risks.

3. Open the CSR in a text editor and copy all of the text.
    Paste the full CSR into the SSL enrollment form in your account.

Thanks

Friday, February 5, 2016

How to use CORS requests in Laravel 5 with middleware

CORS requests in Laravel 5 with middleware:

For this we have to firstly create a middleware with name CORS and write the following code in it.

<?php

namespace App\Http\Middleware;

use Closure;


class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }
}


Now go to the app/Http/kernel.php & add this line in $routeMiddleware

'cors' => \App\Http\Middleware\CORS::class,

Now in route.php we can use is like this



Route::group(['middleware' => 'cors'], function () {
    get('/script', 'ScriptController@getDetail');
    get('/response', 'ScriptController@postDetail');
});


Thanks

Friday, January 29, 2016

Implement asynchronous processes in PHP

Implement asynchronous processes in PHP:


One of the main reasons we need asynchronous processes in PHP is to allow something very time consuming to happen in the background, but not keep the client “on hold” for that entire duration; as PHP is typically synchronous, anything that takes a long time on the server will appear to take a long time for the client.

In that scenario, one solution would be to “detach” the client from the currently loading page, and let them have control of their browser back while the PHP script continues to do it's thing. We should be able to make this happen by sending some headers to the client to say “ok, we’re done here, connection ends”, even though PHP is still running.




class Service
{
    const HEADER_NEW_LINE = "\r\n";

    public function store()
    {
        /*code for reduce process time*/
        self::closeConnection('true');
       //do your code that take much more time e.g. upload a video or import an excel that take more time
    }

    public static function closeConnection($instantOutput = '') {
        set_time_limit(0);
        ignore_user_abort(TRUE);
        header('Connection: close' . self::HEADER_NEW_LINE);
        header('Content-Encoding: none' . self::HEADER_NEW_LINE);
        ob_start();
        echo $instantOutput;
        $size = ob_get_length();
        header('Content-Length: ' . $size, TRUE);
        ob_end_flush();
        ob_flush();
        flush();
    }
}




There are another way to implement asynchronous in php like open socket, log file, fork a curl process etc, but as per my requirement i did choose this 'detach client' method, you are free to choose any method as per your requirement.

Thanks.

Friday, January 15, 2016

How to implement Breadcrumbs in Laravel 5.1

How to implement Breadcrumbs in Laravel 5.1:

Today we will discuss about how to implement Breadcrumbs in Laravel 5.1.

1. Install Laravel Breadcrumbs

Note:-Laravel 5.0 or above is required – use the 2.x version for Laravel 4.

Install with Composer

Run this at the command line:

$ composer require davejamesmiller/laravel-breadcrumbs

This will both update composer.json and install the package into the vendor/ directory.
Add to config/app.php

Add the service provider to providers:



'providers' => [
    // ...
    DaveJamesMiller\Breadcrumbs\ServiceProvider::class,
],

And add the facade to aliases:

'aliases' => [
    // ...
    'Breadcrumbs' => DaveJamesMiller\Breadcrumbs\Facade::class,
],

2. Define your breadcrumbs

Create a file called app/Http/breadcrumbs.php that looks like this:

<?php

// Home
Breadcrumbs::register('home', function($breadcrumbs)
{
    $breadcrumbs->push('Home', route('home'));
});

// Home > About
Breadcrumbs::register('about', function($breadcrumbs)
{
    $breadcrumbs->parent('home');
    $breadcrumbs->push('About', route('about'));
});

// Home > Blog
Breadcrumbs::register('blog', function($breadcrumbs)
{
    $breadcrumbs->parent('home');
    $breadcrumbs->push('Blog', route('blog'));
});

// Home > Blog > [Category]
Breadcrumbs::register('category', function($breadcrumbs, $category)
{
    $breadcrumbs->parent('blog');
    $breadcrumbs->push($category->title, route('category', $category->id));
});

// Home > Blog > [Category] > [Page]
Breadcrumbs::register('page', function($breadcrumbs, $page)
{
    $breadcrumbs->parent('category', $page->category);
    $breadcrumbs->push($page->title, route('page', $page->id));
});




3. Choose a template

By default a Bootstrap-compatible ordered list will be rendered, so if you’re using Bootstrap 3 you can skip this step.

First initialise the config file by running this command:

$ php artisan vendor:publish

Then open config/breadcrumbs.php and edit this line:

'view' => 'breadcrumbs::bootstrap3',

The possible values are:

    Bootstrap 3: breadcrumbs::bootstrap3
    Bootstrap 2: breadcrumbs::bootstrap2
    The path to a custom view: e.g. _partials/breadcrumbs

4. Output the breadcrumbs

Finally, call Breadcrumbs::render() in the view template for each page, passing it the name of the breadcrumb to use and any additional parameters – for example:

{!! Breadcrumbs::render('home') !!}

{!! Breadcrumbs::render('category', $category) !!}


Thanks.

Friday, January 8, 2016

How to get full detail of user's system in php?

Get full detail of user's system in php:

For getting full detail of any user's system (including browser, os etc) we have to use this function.



    public function getDeviceDetail()
    {
        $user = new UserController();
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $os_platform = array();
        $os_array = $user->deviceList();
        foreach ($os_array as $regex => $value) {
            if (preg_match($regex, $user_agent)) {
                $os_platform[] = $regex;
            }
        }
        return $os_platform;
    }




Using this function we will get all the details of any user.

Thanks