Php cache js and css

PHP content caching for javascript and css

I wrote a series of posts about this issue specifically. See Supercharging Javascript in PHP and Supercharging CSS in PHP. These cover:

  • Combining files;
  • Gzipping best practices;
  • Caching best practices; and
  • Versioning output.

Your premise is incorrect. Browsers don’t «see» the PHP file extension and decide not to cache things. See http://www.enhanceie.com/redir/?id=httpperf for information on how browsers really work.

You should set an ETAG on your response, and then you can simply check the If-None-Match request header and return a 304 if the content is unchanged.

Browsers don’t determine if a page or a file is dynamic or static by its extension. Its headers do. Just set the proper headers so the browser knows it can cache the results.

Also, ditch the closing ?> . It’s not required and is bad practice.

PHP content caching for javascript and css, You can also use apache mod_rewrite to refer to these files in the html as js files and redirect the request to the php files, avoiding your server caching issues. Something like this: RewriteEngine On RewriteRule (.*).js $1.php. Put this code in a .htaccess file in your directory.

How do I control client-side caching?

3rd result on google : https://encrypted.google.com/search?sclient=psy&hl=en&site=&source=hp&q=disable+cache+apache&btnG=Google+Search

 FileETag None Header unset ETag Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0" Header set Pragma "no-cache" Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"  

Html — Browser Caching of CSS files, Unless you’ve messed with your server, yes it’s cached. All the browsers are supposed to handle it the same. Some people (like me) might …

XAMPP Server does not load CSS files [duplicate]

Are you using browser caching?

Maybe just try a hard refresh CTRL+F5

Sorry if this is obvious and you have already tried it!

The xampp cannot be the problem, You can verify it by opening the .html file directly in the browser. The possible problem could be you havent set the path for your css file correctly.

or try inline code for testing that your changes are seen properly.

If there is cache problem try open in incognito window

tricky way:
1) open your html file at local host on the browser.
2) now press Shift+ctrl+J to open the console.
3) now you’ll find ‘Source’ option (right-side of console option) at the top of new window.
4) click ‘source’ option and then you»l find your folder having all the .html, .css, .js, .php files available at local host.
5) open the appropriate file (what you what to edit) and modify it.
6) press ctrl+S to save your modification. now you will see the changes.(according to your modification)

Читайте также:  Java load text file

Enable Caching of Javascript, CSS files which are, I am trying to enable browser cache the javascript, css files of my web application. The document type I’m using is a JSP. I see …

How to disable the cache on server side for php file on Apache?

If your hoster has enabled user.ini files you can drop an ini file in your project directory containing:

PHP Manual — Opcache config

Enable caching of css and js files in Apache, While some sites may version assets like images, css and JavaScript so rechecking is a waste of time, not all such sites do this. Ctrl+F5. This is a force …

Источник

Оптимизация, сжатие и кэширование HTML, CSS, JS в PHP

php оптимизация кода

Что это и как это выглядит можно понять на следующем слайде:

Несколько способов оптимизации:

Optimize-2.3.4 — Оптимизация сгенерированного PHP скриптом HTML/XML/JS/CSS кода перед выводом в браузер, оптимизация «на лету» от автора Rin

Возможности оптимизатора HTML/XML кода:

  • удаляет пробелы вначале и в конце переносов строк
  • удаляет пробелы ПОСЛЕ открывающих тагов, если перед тагом есть пробел
  • удаляет пробелы ПЕРЕД закрывающими тагами, если после тага есть пробел
  • удаляет многострочные или большие html комментарии, комментарии в javascript и стилях.
  • корректно обрабатывает таги

Никогда не экономьте на отступах и пробелах в написании кода и ваш КПД увеличится! 🙂 С параметрами по умолчанию программа даёт приемлемое сжатие за небольшое время работы, (баланс между степенью сжатия и скоростью работы) для использования оптимизации «на лету». Скачать Optimize-2.3.4.7z
Сжатие HTML

(?![).)(.*)(?>(?!]).)—>/Uis’,’/[[:blank:]]+/’),array(»,’ ‘),str_replace(array(«n»,»r»,»t»),»,$buf)); > ob_start(‘ob_html_compress’); ?>

 $modified = 0; $offset = 60 * 60 * 24 * 7; header ('Content-type: text/javascript; charset=UTF-8'); header ('vary: accept-encoding'); header ('Cache-Control: max-age=' . $offset); header ('Pragma:'); header ("Last-Modified: ".gmdate("D, d M Y H:i:s", $modified )." GMT"); if(extension_loaded('zlib')) ob_start("compress"); include('init.js'); ob_end_flush(); if(extension_loaded('zlib')) ?>

В init.js файл напишите ваш JavaScript-код и сохранить его в директории, где сохранен js.php
Оптимизация и кэширование CSSсоздайте файл css.php со следующим кодом:

 $mincss = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $mincss); $mincss = str_replace(': ', ':', $mincss); $mincss = str_replace(array("rn",' ',' '), '', $mincss); $mincss = str_replace(';>','>', $mincss); $modified = 0; $offset = 60 * 60 * 24 * 7; if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $modified) < header("HTTP/1.0 304 Not Modified"); header ('Cache-Control:'); >else < header ('Cache-Control: max-age=' . $offset); header ('Content-type: text/css; charset=UTF-8'); header ('Pragma:'); header ("Last-Modified: ".gmdate("D, d M Y H:i:s", $modified )." GMT"); if(extension_loaded('zlib'))ob_start("compress"); echo $mincss; ob_end_flush(); if(extension_loaded('zlib')) > ?>

Источник

Css what is cache in php

My understanding is that Apache webservers cache HTML files (or the HTML produced by php files) by default, but not style or JavaScript files. You can modify existing php files using php’s output control funcitons and write the output to a file which would then be linked from your site.

Apache: How to specify caching for .js and .css files?

I understand that during website development, caching can be disabled entirely at the start of any page using PHP using the directive

if (getenv("DEVELOP")) header("Cache-Control: no-store"); 

But for production use, caching is desired for all files that do not often change.

My understanding is that Apache webservers cache HTML files (or the HTML produced by php files) by default, but not style or JavaScript files.

I further understand that caching for non-HTML files can be specified either in the config file or in an .htaccess file using the directive «Header set Cache-Control». What are some typical ways to do this?

Apache doesn’t cache PHP, the code is executed each time. However the code is compiled into zend vm bytecode provided PHP is loaded into apache as a module and the bytecode is stored until the underlying PHP file is changed. The HTTP header is for the web browsers so they don’t make repeated requests to your server.

If you want to cache dynamic pages on your server using only apache and php you will have to do it yourself. You can do it with php in numerous ways. You can modify existing php files using php’s output control funcitons and write the output to a file which would then be linked from your site. Then you will need to set up a cron, supervisor or systemd job to periodically run the php file(s).

Alternatively some frameworks like laravel will do some caching for you if you configure it to. A very popular solution nowadays is to combine apache with nginx for caching purposes.

Force clients browser cache to clear for php generated pages, For this purpose on JS / CSS I use the ‘Prevent Browser Caching’ plugin and it works great. About clearing generated PHP.

How to Avoid Caching of CSS & JS During Development

Have you ever made changes to a CSS or JS file but then even when you refreshed the Web Duration: 8:56

CSS file is being cached even after clearing cache and changing the CSS version

I have a CSS file and to test it, I added some code to the bottom that just changed the color of a small section on the site. It took about 15 minutes but eventually it loaded and updated the CSS. Then when I removed it to see how long it will take to come off again, the code still loads and it has been about 30 minutes. I tried clearing my browser cache as well as changing the version of the css file. The version (when I inspect the source code on the browser) is updated to v2 like it should be but the file still contains the code from v1. Would it be because of the host caching the file or something? When I ran into this problem before, changing the version of the css file worked but it is not this time. Any help would be much appreciated. Thanks!

Oh as another note I am using the below code to enque the css file and it is in WordPress:

I also know there are other things on stackoverflow but they all just say to either clear the browser cache or to change the version at the end of the css file which both options I have already tried with no success.

@Sahriar Saikat mentioned in the comments that it could be cloudflare caching the file and he was right. I checked the settings in cloudflare (which I didn’t have access to until today) and found that they were using the query level «ignore query string» which was making it not update. Thanks for your help!

Client side cache on css/js, This will cache in the browser but when you make changes in the file filetime will be updated and client will get fresh copy of the file. Share.

Prevent caching of @imported CSS file generated by PHP

In my main.css file, I have a line

tags.css is a css file that is generated by PHP. It returns styles for the colors defined by the users for the various tag types.

In the PHP file, I start with headers that should prevent caching:

 header("Expires: Sun, 01 Jan 2014 00:00:00 GMT"); header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0") header("Cache-Control: post-check=0, pre-check=0"); header("Pragma: no-cache"); header("Content-Type: text/css"); 

However, the browser still caches the css. If I change a tag color, the new css isn’t picked up until I hit shift+refresh.

Because the @import is in a css file, I can’t append a ?t=[timestamp] to the url (as far as I know), and changing it manually with ?v=[version] doesn’t help because it’s the users changing the colors independently of the code being updated.

Note: I have also tried putting the anti-caching headers in the apache2 virtual host configuration file, but that didn’t seem to help either.

How can I prevent this css file from being cached?

You could try redirecting to include a timestamp in the url if none is present when intially requested:

PHP How to not cache generated HTML but cache static data like, PHP How to not cache generated HTML but cache static data like images/js/css Many PHP developers add the no-cache header on top of their PHP

Источник

Кэширование контента в файлы PHP

Кэширование контента в файлы PHP

Для ускорения работы PHP-сайта можно применить механизм единоразового сохранения сформированного контента в файлах кэша для их повторного использования, например меню сайта, «тяжелый» вывод выгрузки из базы данных и т.д. Для этих целей был написан небольшой статический PHP-класс для кэширования блоков контента или страниц целиком основанный на буферизации вывода в переменную.

Код файла cache.php

 else < self::$keys[] = $name; return false; >> else < return ''; >> /** * Отправка данных в кэш. */ public static function set($content) < if (self::$enable) < $name = array_pop(self::$keys); $dir = __DIR__ . self::$path . '/'; if (!is_dir($dir)) < @mkdir($dir, 0777, true); >file_put_contents($dir . '/' . $name . '.tmp', $content); > return $content; > /** * Начало кэширования фрагмента. */ public static function begin($name) < if ($content = self::get($name)) < echo $content; return false; >else < ob_start(); return true; >> /** * Завершение кэширования фрагмента. */ public static function end() < echo self::set(ob_get_clean()); >/** * Очистка кэша. */ public static function clear() < $dir = __DIR__ . self::$path; foreach (glob($dir . '/*') as $file) < if (is_file($file)) < unlink($file); >> > >

Использование

// Подключаем файл класса require_once ‘/cache.php’; // Кэшируем фрагмент кода if (Cache::begin(‘test’)) < ?>

Теперь, если в папке cache нет файла test.tmp, то условие выполнится, контент выведется и сохранится в файле. В другом случаи контент всегда будет выводится из файла кэша.

Источник

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