sudo composer update

sudo composer update

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.

Unable to upload large file in website

Unable to upload large file in php website, here is setting for htaccess file, after this you can upload 500 mb file size, and also change this value.

php_value upload_max_filesize 5000M
php_value post_max_size 5000M
php_value memory_limit 256M
php_value max_execution_time 300
php_value max_input_time 300

404 redirect to homepage wordpress

if( !function_exists('redirect_404_to_homepage') ){

    add_action( 'template_redirect', 'redirect_404_to_homepage' );

    function redirect_404_to_homepage(){
       if(is_404()):
            wp_safe_redirect( home_url('/') );
            exit;
        endif;
    }
}

Laravel spatie permissions and roles

Direct Permissions

composer show spatie/laravel-permission

A permission can be given to any user:

$user->givePermissionTo('edit articles');

// You can also give multiple permission at once
$user->givePermissionTo('edit articles', 'delete articles');

// You may also pass an array
$user->givePermissionTo(['edit articles', 'delete articles']);

A permission can be revoked from a user:

$user->revokePermissionTo('edit articles');

Or revoke & add new permissions in one go:

$user->syncPermissions(['edit articles', 'delete articles']);

You can check if a user has a permission:

$user->hasPermissionTo('edit articles');

Or you may pass an integer representing the permission id

$user->hasPermissionTo('1');
$user->hasPermissionTo(Permission::find(1)->id);
$user->hasPermissionTo($somePermission->id);

You can check if a user has Any of an array of permissions:

$user->hasAnyPermission(['edit articles', 'publish articles', 'unpublish articles']);

…or if a user has All of an array of permissions:

$user->hasAllPermissions(['edit articles', 'publish articles', 'unpublish articles']);

You may also pass integers to lookup by permission id

$user->hasAnyPermission(['edit articles', 1, 5]);

Saved permissions will be registered with the Illuminate\Auth\Access\Gate class for the default guard. So you can check if a user has a permission with Laravel’s default can function:

$user->can('edit articles');

WordPress best performance .htaccess file content

# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript


#BEGIN EXPIRES HEADERS
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default expiration: 1 hour after request
ExpiresDefault "now plus 1 hour"
# CSS and JS expiration: 1 week after request
ExpiresByType text/css "now plus 1 week"
ExpiresByType application/javascript "now plus 1 week"
ExpiresByType application/x-javascript "now plus 1 week"
# Image files expiration: 1 month after request
ExpiresByType image/bmp "now plus 1 month"
ExpiresByType image/gif "now plus 1 month"
ExpiresByType image/jpeg "now plus 1 month"
ExpiresByType image/jp2 "now plus 1 month"
ExpiresByType image/pipeg "now plus 1 month"
ExpiresByType image/png "now plus 1 month"
ExpiresByType image/svg+xml "now plus 1 month"
ExpiresByType image/tiff "now plus 1 month"
ExpiresByType image/vnd.microsoft.icon "now plus 1 month"
ExpiresByType image/x-icon "now plus 1 month"
ExpiresByType image/ico "now plus 1 month"
ExpiresByType image/icon "now plus 1 month"
ExpiresByType text/ico "now plus 1 month"
ExpiresByType application/ico "now plus 1 month"
# Webfonts
ExpiresByType font/truetype "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType application/x-font-woff "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
</IfModule>
#END EXPIRES HEADERS

# BEGIN Cache-Control Headers
<ifModule mod_headers.c>
 <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
 Header set Cache-Control "max-age=2592000, public"
 </filesMatch>
 <filesMatch "\.(css)$">
 Header set Cache-Control "max-age=604800, public"
 </filesMatch>
 <filesMatch "\.(js)$">
 Header set Cache-Control "max-age=216000, private"
 </filesMatch>
 <filesMatch "\.(x?html?|php)$">
 Header set Cache-Control "max-age=600, private, must-revalidate"
 </filesMatch>
</ifModule>
# END Cache-Control Headers


# ENABLE LITESPEED CACHE START
<IfModule LiteSpeed>
CacheEnable public
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^GET|HEAD$
RewriteCond %{HTTP_HOST} ^sample.com|sample.net|sample.org [NC]
RewriteCond %{REQUEST_URI} !login|admin|register|post|cron
RewriteCond %{QUERY_STRING} !nocache
RewriteRule .* - [E=Cache-Control:max-age=300]
</IfModule>
# ENABLE LITESPEED CACHE END

# START ENABLE KEEP ALIVE
<ifModule mod_headers.c>
Header set Connection keep-alive
</ifModule>
# END ENABLE KEEP ALIVE


<IfModule pagespeed_module>
ModPagespeed on
ModPagespeedEnableFilters rewrite_css,combine_css
ModPagespeedEnableFilters recompress_images
ModPagespeedEnableFilters convert_png_to_jpeg,convert_jpeg_to_webp
ModPagespeedEnableFilters collapse_whitespace,remove_comments
</IfModule>

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
</IfModule>

in_array for multidimensional array in PHP or Laravel

{{ in_array($d->id, array_column(json_decode($notes),'user_id')) }}
{{ count(array_keys(array_column(json_decode($notes),'user_id'), $d->id)) }}
$userdb = Array
(
    (0) => Array
        (
            ('uid') => '100',
            ('name') => 'Sandra Shush',
            ('url') => 'urlof100'
        ),

    (1) => Array
        (
            ('uid') => '5465',
            ('name') => 'Stefanie Mcmohn',
            ('url') => 'urlof5465'
        ),

    (2) => Array
        (
            ('uid') => '40489',
            ('name') => 'Michael',
            ('url') => 'urlof40489'
        )
);

$url_in_array = in_array('urlof5465', array_column($userdb, 'url'));

if($url_in_array) {
    echo 'value is in multidim array';
}
else {
    echo 'value is not in multidim array';
}

how to check app is installed or not in android using JavaScript | Check if android app is installed from web page browser

To avoid this or to avoid connect your app to some url you can do another trick to implement this using PHP and JS.

  1. You must create an intent-filter on your app’s main activity like this:
<intent-filter android:label="filter_react_native">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="MyCustomScheme" android:host="MyCustomHost" />
</intent-filter>
  1. Create PHP file redirect_to_app.php which will work in case user have the app installed.
<?php
header('Location: MyCustomScheme://MyCustomHost');
  1. Create HTML/PHP file check_redirect_to_app.php which must be shown for users which didn’t install your app yet.
...
<a href="https://play.google.com/store/apps/details?id=YOUR_APP_PACKAGE_NAME">Please install the application</a>
...

<script>
    location.href = '...redirect_to_app.php';
</script>
  1. Redirect users to check_redirect_to_app.phpcheck_redirect_to_app.php will try to redirect to MyCustomScheme://MyCustomHost automatically. In case it will not find such a app, it will coninue to show check_redirect_to_app.php content.

php artisan list command in Laravel | Laravel command to check Laravel Version

Laravel Framework 8.60.0

Usage:
command [options] [arguments]

Options:
-h, –help Display help for the given command. When no command is given display help for the list command
-q, –quiet Do not output any message
-V, –version Display this application version
–ansi|–no-ansi Force (or disable –no-ansi) ANSI output
-n, –no-interaction Do not ask any interactive question
–env[=ENV] The environment the command should run under
-v|vv|vvv, –verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
clear-compiled Remove the compiled class file
db Start a new database CLI session
down Put the application into maintenance / demo mode
env Display the current framework environment
help Display help for a command
inspire Display an inspiring quote
list List commands
migrate Run the database migrations
optimize Cache the framework bootstrap files
serve Serve the application on the PHP development server
test Run the application tests
tinker Interact with your application
up Bring the application out of maintenance mode
auth
auth:clear-resets Flush expired password reset tokens
cache
cache:clear Flush the application cache
cache:forget Remove an item from the cache
cache:table Create a migration for the cache database table
config
config:cache Create a cache file for faster configuration loading
config:clear Remove the configuration cache file
db
db:seed Seed the database with records
db:wipe Drop all tables, views, and types
event
event:cache Discover and cache the application’s events and listeners
event:clear Clear all cached events and listeners
event:generate Generate the missing events and listeners based on registration
event:list List the application’s events and listeners
key
key:generate Set the application key
make
make:cast Create a new custom Eloquent cast class
make:channel Create a new channel class
make:command Create a new Artisan command
make:component Create a new view component class
make:controller Create a new controller class
make:event Create a new event class
make:exception Create a new custom exception class
make:factory Create a new model factory
make:job Create a new job class
make:listener Create a new event listener class
make:mail Create a new email class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:notification Create a new notification class
make:observer Create a new observer class
make:policy Create a new policy class
make:provider Create a new service provider class
make:request Create a new form request class
make:resource Create a new resource
make:rule Create a new validation rule
make:seeder Create a new seeder class
make:test Create a new test class
migrate
migrate:fresh Drop all tables and re-run all migrations
migrate:install Create the migration repository
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
migrate:status Show the status of each migration
model
model:prune Prune models that are no longer needed
notifications
notifications:table Create a migration for the notifications table
optimize
optimize:clear Remove the cached bootstrap files
package
package:discover Rebuild the cached package manifest
passport
passport:client Create a client for issuing access tokens
passport:hash Hash all of the existing secrets in the clients table
passport:install Run the commands necessary to prepare Passport for use
passport:keys Create the encryption keys for API authentication
passport:purge Purge revoked and / or expired tokens and authentication codes
permission
permission:cache-reset Reset the permission cache
permission:create-permission Create a permission
permission:create-role Create a role
permission:setup-teams Setup the teams feature by generating the associated migration.
permission:show Show a table of roles and permissions per guard
queue
queue:batches-table Create a migration for the batches database table
queue:clear Delete all of the jobs from the specified queue
queue:failed List all of the failed queue jobs
queue:failed-table Create a migration for the failed queue jobs database table
queue:flush Flush all of the failed queue jobs
queue:forget Delete a failed queue job
queue:listen Listen to a given queue
queue:monitor Monitor the size of the specified queues
queue:prune-batches Prune stale entries from the batches database
queue:prune-failed Prune stale entries from the failed jobs table
queue:restart Restart queue worker daemons after their current job
queue:retry Retry a failed queue job
queue:retry-batch Retry the failed jobs for a batch
queue:table Create a migration for the queue jobs database table
queue:work Start processing jobs on the queue as a daemon
route
route:cache Create a route cache file for faster route registration
route:clear Remove the route cache file
route:list List all registered routes
sail
sail:install Install Laravel Sail’s default Docker Compose file
sail:publish Publish the Laravel Sail Docker files
schedule
schedule:list List the scheduled commands
schedule:run Run the scheduled commands
schedule:test Run a scheduled command
schedule:work Start the schedule worker
schema
schema:dump Dump the given database schema
session
session:table Create a migration for the session database table
storage
storage:link Create the symbolic links configured for the application
stub
stub:publish Publish all stubs that are available for customization
vendor
vendor:publish Publish any publishable assets from vendor packages
view
view:cache Compile all of the application’s Blade templates
view:clear Clear all compiled view files

how can i protect laravel api calling from other website

Access-Control-Allow-Origin https://mydomain.com/

 added a new middleware

<?php

namespace App\Http\Middleware;

use Closure;

class VerifyAPIAccess
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (
            !(App::environment('local'))
            && (
                !$request->header('access-token')
                || $request->header('access-token') !== env('APP_API_TOKEN')
            )
        ) {
            return response()->json(['Message' => 'You do not access to this api.'], 403);
        }

        return $next($request);
    }
}

and then added to my route

Route::group([
    'middleware' => [
        VerifyAPIAccess::class,
 	'throttle:60,1'
    ]
], function () {

// list some routes

});

you could also restrict access by adding throttling which would stop someone from hammering your API, with token or not.

There are probably many approaches. A simple but effective one would be sessions. You can save the user in a session. This way you can also count his Api accesses. As soon as they are larger than allowed, you can block their requests. You also write the block in the session. But pay attention to the session duration. It must be long enough.

But the user with bad intentions can get a new session. To avoid this, you can also put his IP on an internal blacklist for a day.

Note: But an open api is always a point of attack.

Things tried:

  • Using passport to protect my routes and then use passport’s CreateFreshApiToken middleware. Protection works fine, unauthorized users are not able to access the routes, however I don’t get laravel_token in my cookies and therefore I can’t get access to that route if I’m not logged in.
  • Use passport’s client credentials grant access. Works fine and the way I want it to work but doesn’t really make sense because if I hardcode the client_secret – anyone can access it and then use it to access protected routes. If I make a proxy-like solution, to call a controller method, which would issue a valid token and thus not exposing client_secret to front-end but then anyone could just call that route which issues the token and it would be pointless once again.

You cannot stop people from trying to access of publicly visible API. You need to secure the API and only respond to those with the proper access privileges. 

429 too many requests laravel 8

I stumbled upon the same problem today and did some debugging. When registering the /login route, Fortify applies the Illuminate\Routing\Middleware\ThrottleRequests:login middleware to it. This means, for every request to that route, the ThrottleRequests middleware will call the RateLimiter instance for that specified key. Apparently, Fortify doesn’t register a RateLimiter for the login key.

Due to the missing key in the $limiters property of the RateLimiter instance, the ThrottleRequests middleware uses its default fallback, which doesn’t handle the edge case “there SHOULD be a rate limiter for that key, but there isn’t.” really well. The $maxAttempts variable is set to 0 and will result in flaky rate limiting behaviour.

I feel like this is a bug in Fortify, because rate limiting is also happening in the \Laravel\Fortify\Actions\EnsureLoginIsNotThrottled action, which is invoked in the \Laravel\Fortify\Http\Controllers\AuthenticatedSessionController controller. I didn’t check this on a fresh Laravel installation, though, so I don’t want to jump to conclusions here.

Anyway, long story short: As a workaround, you can simply register a rate limiter for the “login” key in some of your providers, e. g. AppServiceProvider or AuthServiceProvider:

public function boot()
{
    RateLimiter::for("login", function () {
        Limit::perMinute(5);
    });
}

Edit: I just realized that the rate limiter for the “login” key is indeed provided by Fortify within the FortifyServiceProvider class. If you happen to have a problem similar to the one discussed above, make sure that you added the FortifyServiceProvider class to your providers array in the config/app.php.

source : stackoverflow