Php script clear cache

How to Clear cache in Laravel 10/9/8/7

In this simple tutorial I will show you how to clear cache in Laravel application easily. I will also show you the artisan commands to run and I will also show you how you can create a simple function to clear cache via web url.

Why clear cache in Laravel?

Sometimes you make certain changes to your Laravel config or views but changes do not reflect in your app console or in the frontend. This may primarily happen because many elements, specially some of your app’s configuration, routes and media such as images, Javascript, CSS are served by Laravel application cache. So it becomes essential to clear cache in Laravel application to see latest changes in effect.

Clear Cache in Laravel using CLI (Terminal)

Open a terminal in your Laravel application root directory. You can run the following commands to clear various types of cache in Laravel:

1. Clear Application Cache

Run the following command to clear application cache in Laravel application.

2. Clear Route Cache

To clear route cache of your Laravel application execute the following command.

Читайте также:  Mac os установка java 11

3. Clear Config Cache

You can use config:clear to clear the config cache of the Laravel application.

4. Clear Compiled View Cache

Also, you may need to clear compiled view files of your Laravel application. To clear compiled view files run the following command from the terminal.

In addition, Laravel provides Artisan command to precompile all of the views used by your application. So can clear and rebuild all view cache:

$ php artisan view:cache Compiled views cleared! Blade templates cached successfully!

5. Events Cache

If you are using Events in your Laravel application, it is recommended to cache your Events, so that Laravel framework does not need to scan all of your event listeners on every request.

$ php artisan event:clear Cached events cleared!

6. Clear ALL Cache

The last but not the least one. You can clear ALL; config, view, application, routes, events cache & compiled services and packages files, in a single go:

php artisan optimize:clear
Cached events cleared! Compiled views cleared! Application cache cleared! Route cache cleared! Configuration cache cleared! Compiled services and packages files removed! Caches cleared successfully!

Clear Cache in Laravel (via URL)

This is useful where you don’t have access to cli. For example, shared hosting may not provide ssh access to server. In this case, you can write s small anonymous function, bind it to a route and call it in your browser.

Create a new route in your routes/web.php route file of your Laravel Application with code:

Route::get('/clear-cache', function() < Artisan::call('cache:clear'); Artisan::call('route:clear'); Artisan::call('config:clear'); Artisan::call('view:clear'); Artisan::call('event:clear'); return "All Cache was cleared"; >);
Route::get('/clear-cache', function() < Artisan::call('optimize:clear'); echo Artisan::output(); >);

The result of last one should be the same as the CLI command php artisan optimize:clear above.

Conclusion

This tutorial demonstrates with help of examples to clear cache in Laravel framework using command line interface (CLI) and PHP script. Clearing cache in Laravel is safe because when you clear the cache the application starts creating new cache again.

Also Read

Clear template cache in x-cart Have you been making changing into a smarty template file (within x-cart and…

Clearing Activacollab 3.x cache through script With upgrading to AC3 the old clear_cache_by_pattern(«*») stopped working. There’s option at admin…

How to Create Custom Route File in Laravel 8 Routes are entry points to a Laravel application. There are two route files…

How to Create Custom Log File in Laravel In Laravel logs are written to storage/logs/laravel.log file by default. You can tag…

Источник

opcache_reset

Функция сбрасывает весь кеш. После вызова opcache_reset() все скрипты будут заново загружены, скомпилированы и помещены в кеш после их следующего вызова. Функция сбрасывает только кеш в памяти, не затрагивая файловый кеш.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает true , если кеш опкодов был сброшен или false , если кеш отключён, ожидается перезапуск или перезапуск выполняется (смотрите opcache_get_status() ).

Смотрите также

User Contributed Notes 7 notes

My workaround to clear cache via CLI is create a bash script like this:

put it in /usr/local/bin/opcache-clear and make it executable.
When I want to clear cache I simply run «opcache-clear» inside terminal.

It should be mentioned that opcache_reset() does not reset cache when executed via cli.
So `php -r «var_dump(opcache_reset());»` outputs «true» but doesn’t clean cache. Make file, access it via http — and cache is clean.

In some (most?) systems PHP’s CLI has a separate opcode cache to the one used by the web server or PHP-FPM process, which means running opcache_reset() in the CLI won’t reset the webserver/fpm opcode cache, and vice-versa.

For longer php scripts: opcache_reset() will obtain a lock and it will reset the cache only after the script has ended, after which the lock is released.

Calling opcache_reset() multiple times or any other opcache manipulation method, like opcache_invalidate(), after calling opcache_reset() in a single script is not useful: while opcache_reset() holds the lock, other opcache methods will return false and they will have zero effect on the cache.

Although the opcache manipulation methods have no effect during this lock, opcache does recache scripts corresponding to the opcache.revalidate_freq setting, provided that opcache.validate_timestamps is switched on.

To keep the cache up to date, use opcache_invalidate() when modifying single php files. Use opcache_reset() for bigger changes and only at the end of a php script.

So, I thought I’d share something that might benefit those looking for a way to reset opcache in CLI.

As an example in my case, I’m running a Laravel app with a router script with the built-in web server for local development. I enabled opcache with the following run configuration:

/path/to/php.exe -d zend_extension=php_opcache.dll -d opcache.enable_cli=1 -d opcache.memory_consumption=128 -d opcache.max_accelerated_files=10000 -d opcache.validate_timestamps=0 -d opcache.save_comments=0 -t project_path/public/ server.php

This is basically what artisan serve is doing behind the scenes, anyway, except without the opcache part.

I have some file watchers setup to detect changes and executes the following upon said change(s):

/path/to/php.exe -d zend_extension=php_opcache.dll -d opcache.enable_cli=1 -r «opcache_reset();»

The key is ensuring that you’re enabling opcache in CLI. I’ve been using this for some time, so I can attest to this being a viable solution without needing to create a script to execute somewhere in the document root, etc.

I’m only referring to Laravel as an example of why I chose to explore options for solving this problem. This should translate to any scenario a developer would need to utilize opcache in their project(s) while using the built-in web server.

For people who have difficulties with constants and opcache_reset().
If you include a file with constant and do an opcache_reset() in the same file, you’ll probably have some error like :

«Notice: Constant already defined»

The trick is to call opcache_reset() in an isolated file, then include another file that include the file with constants.

File a.php
opcache_reset ();
include ‘b.php’
?>

File b.php
include ‘constants.php’ ;
?>

File constants.php
define ( ‘MY_CONST’ , ‘abcdef’ );
?>

With this trick, the opcache will be reset in a.php and when b.php will be included, the constants will not be in cache anymore.

Источник

PHP clearstatcache() Function

Output file size, truncate file, clear cache, and then output file size again:

$file = fopen(«test.txt», «a+»);
// truncate file
ftruncate($file,100);
fclose($file);

//Clear cache and check filesize again
clearstatcache();
echo filesize(«test.txt»);
?>

The output of the code above could be:

Definition and Usage

The clearstatcache() function clears the file status cache.

PHP caches data for some functions for better performance. If a file is to be checked several times in a script, you probably want to avoid caching to get correct results. To do this, use the clearstatcache() function.

Syntax

Parameter Values

Parameter Description
clear_realpath_cache Optional. Indicates whether to clear the realpath cache or not. Default is FALSE, which indicates not to clear realpath cache
filename Optional. Specifies a filename, and clears the realpath and cache for that file only

Tips and Notes

Tip: Functions that are caching:

Technical Details

Return Value: Nothing
PHP Version: 4.0+
PHP Changelog: PHP 5.3 — Added two optional parameters: clear_realpath_cahe and filename

❮ PHP Filesystem Reference

Источник

Оцените статью