Tuesday, June 27, 2017

Laravel 5: How to modify Request values | How to "artificially" add values to Request array | How to dynamically add params to Request array

Laravel 5: How to modify Request values | How to "artificially" add values to Request array | How to dynamically add params to Request array. You can use the merge() method on the $request object. In spite of the methods name, it actually replaces any values associated with the member names specified by the keys of the parameter rather than concatenating their values or anything like that. 

A few times I encountered a situation – a store() or update() method with Request parameter, but I needed to add some additional value to the request before calling Eloquent functions. So how to do that? Apparently, pretty easy.

use Illuminate\Http\Request;

protected $request;

public function __construct(Request $request)
{
    $this->request = $request;

}

$this->request->merge(["custom" => "New Custom Value"]);






..

Monday, June 26, 2017

Validating a URL in PHP

Check if the variable $url is a valid URL:

The FILTER_VALIDATE_URL filter validates a URL.

Possible  flags:

FILTER_FLAG_SCHEME_REQUIRED - URL must be RFC compliant.
Like http://example

FILTER_FLAG_HOST_REQUIRED - URL must include host name.
Like http://www.example.com

FILTER_FLAG_PATH_REQUIRED - URL must have a path after domain.
Like www.example.com/example1/

FILTER_FLAG_QUERY_REQUIRED - URL must have a query string.
Like "example.php?name=Peter&age=37"

filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)


Set floating div to height: 100% | Div as Table | Responsive Table | Table Table-Row Table-Cell | Table Div

lefttttttttttttttttttttttttt
middleeeeeeeeeeeeeeeeeeeeeee
rightttttttttttttttttttttttt

You could do it by setting up a table-like structure of <div> elements in your HTML and then using display: "table", "table-row" and "table-cell". This will work because table cells in the same row automatically resize to the same height as the tallest cell. However, IE7 will not support table properties.

<div id="table">
    <div id="table-tr">
        <div id="table-td">
            lefttttttttttttttttttttttttt
        </div>
        <div id="table-td">
            middleeeeeeeeeeeeeeeeeeeeeee
        </div>
        <div id="table-td">
            rightttttttttttttttttttttttt
        </div>
    </div>
</div>

<style type="text/css">
#table {
    background-color: red;
    width: 300px;
    height: 120px;
    overflow: auto;
    padding: 1px;
    display: table;
    table-layout:fixed;
}

#table-tr {
    display: table-row;
}

#table-td {
    width: 33.34%;
    display: table-cell;
    background-color: #ccc;
    border: 1px solid red;
    word-wrap: break-word;
    padding: 3px;
}
</style>

Sunday, June 25, 2017

PHP Class for HTTP Response Status Codes

HTTP Response Status Codes:

<?php
class HttpStatusCodeUtils
{
    // [Informational 1xx]
    const HTTP_CONTINUE = 100;
    const HTTP_SWITCHING_PROTOCOLS = 101;
    // [Successful 2xx]
    const HTTP_OK = 200;
    const HTTP_CREATED = 201;
    const HTTP_ACCEPTED = 202;
    const HTTP_NONAUTHORITATIVE_INFORMATION = 203;
    const HTTP_NO_CONTENT = 204;
    const HTTP_RESET_CONTENT = 205;
    const HTTP_PARTIAL_CONTENT = 206;
    // [Redirection 3xx]
    const HTTP_MULTIPLE_CHOICES = 300;
    const HTTP_MOVED_PERMANENTLY = 301;
    const HTTP_FOUND = 302;
    const HTTP_SEE_OTHER = 303;
    const HTTP_NOT_MODIFIED = 304;
    const HTTP_USE_PROXY = 305;
    const HTTP_UNUSED = 306;
    const HTTP_TEMPORARY_REDIRECT = 307;
    // [Client Error 4xx]
    const HTTP_BAD_REQUEST = 400;
    const HTTP_UNAUTHORIZED = 401;
    const HTTP_PAYMENT_REQUIRED = 402;
    const HTTP_FORBIDDEN = 403;
    const HTTP_NOT_FOUND = 404;
    const HTTP_METHOD_NOT_ALLOWED = 405;
    const HTTP_NOT_ACCEPTABLE = 406;
    const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
    const HTTP_REQUEST_TIMEOUT = 408;
    const HTTP_CONFLICT = 409;
    const HTTP_GONE = 410;
    const HTTP_LENGTH_REQUIRED = 411;
    const HTTP_PRECONDITION_FAILED = 412;
    const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
    const HTTP_REQUEST_URI_TOO_LONG = 414;
    const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
    const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const HTTP_EXPECTATION_FAILED = 417;
    // [Server Error 5xx]
    const HTTP_INTERNAL_SERVER_ERROR = 500;
    const HTTP_NOT_IMPLEMENTED = 501;
    const HTTP_BAD_GATEWAY = 502;
    const HTTP_SERVICE_UNAVAILABLE = 503;
    const HTTP_GATEWAY_TIMEOUT = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;


    private static $messages = array(
        // [Informational 1xx]
        100 => '100 Continue',
        101 => '101 Switching Protocols',
        // [Successful 2xx]
        200 => '200 OK',
        201 => '201 Created',
        202 => '202 Accepted',
        203 => '203 Non-Authoritative Information',
        204 => '204 No Content',
        205 => '205 Reset Content',
        206 => '206 Partial Content',
        // [Redirection 3xx]
        300 => '300 Multiple Choices',
        301 => '301 Moved Permanently',
        302 => '302 Found',
        303 => '303 See Other',
        304 => '304 Not Modified',
        305 => '305 Use Proxy',
        306 => '306 (Unused)',
        307 => '307 Temporary Redirect',
        // [Client Error 4xx]
        400 => '400 Bad Request',
        401 => '401 Unauthorized',
        402 => '402 Payment Required',
        403 => '403 Forbidden',
        404 => '404 Not Found',
        405 => '405 Method Not Allowed',
        406 => '406 Not Acceptable',
        407 => '407 Proxy Authentication Required',
        408 => '408 Request Timeout',
        409 => '409 Conflict',
        410 => '410 Gone',
        411 => '411 Length Required',
        412 => '412 Precondition Failed',
        413 => '413 Request Entity Too Large',
        414 => '414 Request-URI Too Long',
        415 => '415 Unsupported Media Type',
        416 => '416 Requested Range Not Satisfiable',
        417 => '417 Expectation Failed',
        // [Server Error 5xx]
        500 => '500 Internal Server Error',
        501 => '501 Not Implemented',
        502 => '502 Bad Gateway',
        503 => '503 Service Unavailable',
        504 => '504 Gateway Timeout',
        505 => '505 HTTP Version Not Supported'
    );


    public static function httpHeaderFor($code)
    {
        return 'HTTP/1.1 ' . self::$messages[$code];
    }


    static function getMessageForCode($code)
    {
        return isset(self::$messages[$code]) ? self::$messages[$code] : "$code Invalid Request";
    }

    static function isError($code)
    {
        return is_numeric($code) && $code >= self::HTTP_BAD_REQUEST;
    }

    static function canHaveBody($code)
    {
        return
            // True if not in 100s
            ($code < self::HTTP_CONTINUE || $code >= self::HTTP_OK)
            && // and not 204 NO CONTENT
            $code != self::HTTP_NO_CONTENT
            && // and not 304 NOT MODIFIED
            $code != self::HTTP_NOT_MODIFIED;
    }
}
?>


PHP: Import variables into the current symbol table from an array

PHP: Import variables into the current symbol table from an array

$params = array("x1" => "VALUE OF X1");
extract($params);
echo (isset($x1) ? "X1=".$x1 : "NO X1 DEFINED") . "<BR>";
echo (isset($x2) ? "X2=".$x2 : "NO X2 DEFINED") . "<BR>";

And output would be following:

X1=VALUE OF X1
NO X2 DEFINED


Laravel 5: Generate a URL to a controller action

It's easy to generate a URL as like Controller Action. Suppose you have a controller named "UserController" and have an action inside the Controller named "customerLogin" and in routes.php you mentioned the router as: 

"Route::get("login_customer", "UserController@customerLogin"

So when you browse www.domain.com/login_customer then actually executed "customerLogin" action of "UserController".

Now for some reason you need to construct a URL based on Controller and Action, then you can apply below to generate URL:

action('UserController@customerLogin', ['id' => "3 0"])

Will generate below URL:

www.domain.com/login_customer?id=3+0

If you Controller exists inside another folder then you ca

action('Folder\UserController@customerLogin', ['id' => "3 0"])


Laravel 5: Use of Laravel Middleware WEB | API | THROTTLE

You have to create a middleware first. Create a php file named "ApiFilter.php" in "app/Http/Middleware" folder with following contents:


<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request as HttpRequest;

class ApiFilter
{
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle(HttpRequest $request, Closure $closure)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            }
            else {
                return redirect()->guest('login');
            }
        }
        return $closure($request);
    }
}


Now you have to register this middleware to your project. Need to open "App\Http\Kernel.php" file. If you want to register this middleware for global scope then you have to add the below line as follows:


protected $middleware = [
    \App\Http\Middleware\ApiFilter::class
];


So when you browse any url in your project scope, this middleware can handle them.

But if you want to the middleware for specific area you have to add the middleware to "$middlewareGroups" as follows:


protected $middlewareGroups = [
    'web' => [
        .....
    ],

    'api' => [
        'throttle:3,1',
        \App\Http\Middleware\ApiFilter::class
    ],
];


Now add the following lines to "app\Http\routes.php":


Route::group(["middleware" => "api", "prefix" => "api"], function() {
    Route::get('action_name', 'ApiController@action_name');
});


If you browse "www.domain.com/api/action_name" it will pass through ApiFilter middleware bacause of prefix "api" used. But if you only browse "www.domain.com/action_name" it will pass through another middleware.



These middleware may be assigned to groups or used individually


protected $routeMiddleware = [
    'my_middleware' => \App\Http\Middleware\Authenticate::class
];

And can be used as below:

Route::group(['middleware' => 'my_middleware'], function() {
    Route::get('landing-page', 'MyController@landingPage');
});


We can use "throttle" which will restrict request overloading. Here we used "throttle:3,1" means per minute 3 request can be granted, if more request send request rejected as below image:

We need to add below line to "routeMiddleware" for "throttle" action:


protected $routeMiddleware = [
    .........,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];