javascript file not being cached? - php

I'm trying to optimize my web application and unfortunately have ended up with a javascript file size of around 450K - that too after compressing [it would take a while for me to redo the javascripting but until then I have to go live] - I initially had made a number of small javascript libraries to work upon. And what I do is I have a php file which includes all the javascript files and then I included my php file as below:
<script language="js/js.php"></script>
The thing is that I was hoping that my file would be cached upon the first load but it seems every time I refresh the page or come back to it the file is reloaded from the server - I checked this using firebug. Is there anything else that I must add to ensure that my file is cached on the user end.. or am I misunderstanding the idea of a cache here?

You'll need to set some headers in php to ensure the file is cached.
At the top of js.php put:
ob_start("ob_gzhandler");
$expires = 2678400; // 1 month in seconds
header("Pragma: public");
header("Cache-Control: maxage=".$expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
That will add both basic caching + gzip compression on the fly.

Why not to leave it .js file and let web-server take care of caching?
Compression is not the thing you really need but Conditional Get is

Related

(with )Wrapped css,js cache is not working with even same url

How Wrapper class works
I created php class and now I am able to do this to put together all my css,js .It works like this Wrap::set(array(file.css,file2.css,file3.css)) then I wrote wrap::call_path and it begin to generate url like this www.example.com/wrap_contects?path[]=file.css&path[]=file2.css&path[]=file3.css
then in the server side I get all paths with in the array then I tried file_get_content for each of them,after that I wrote echo all results.It put together all CSS,if I wrote JS it will be JS.
Problem
Problem is browser is not cache this url.
Note
I consider all security issues,I created token to send wrap_content.php to prevent file get content to work for any file that user request
I solved this problem,hope it will help someone who has same problem to solve this problem in the future
I added these ones to wrap_contents.php:
$cache_length=60*24*30;
$cache_expire_date = gmdate("D, d M Y H:i:s", time() + $cache_length);
header("Expires: $cache_expire_date");
header("Pragma: cache");
header("Cache-Control: max-age=2592000");
(if css) header("Content-type: text/css");
(if js) header('Content-Type: application/javascript');
This created css,js simulator on the response with php file.

PHP: Unlink a little too effective

I'm in the process of developing a PHP webpage that constructs a .SVG file from a SQL database on the fly, embeds it in the page, and enables a user to interact with it. These temporary files take on the form SVG[RandomNumber].svg and the unlink function successfully deletes the files with no error messages.
Here's the problem: I assumed that if I invoked the unlink function after the SVG file had loaded for the user, the webpage would be unaffected since the user's browser would have cached the file or whatnot. Everything works perfectly when no unlink command is present in the code; however, 'unlinking' anywhere -- even at the end of the webpage, causes no object to show at all. In Firefox there's no trace of the object, and in IE I receive the error "The webpage cannot be found."
So have I deleted the file before the browser uploads it? What's the best way to deal with the general situation?
Thank you.
It might be useful to change workflow and don't create temporaries. When image is used only once or it's generation is not a big deal you can try to generate it on-the-fly in following fashion
<?php
// We'll be outputting a SVG
header('Content-type: Content-Type: image/svg+xml');
// It will be called image.svg
header('Content-Disposition: attachment; filename="image.svg"');
// Don't cache
header("Cache-Control: no-cache, must-revalidate");
header("Expires: " . date("D, j M Y H:i:s"));
// The PDF source is in original.pdf
generate_svg_from_db('image.svg');
?>

How to update browser cache from PHP?

I have a PHP file get_css.php which generates CSS code more than 60 KB long. This code does not change very often. I want this code to be cached in user's browser.
Now, when i visit a HTML page several times which includes get_css.php url to fetch css, my browser is loading all CSS contents from the server each time i visit the page.
Browsers should get the contents from server only if the CSS code is changed on server side. If the css code is not changed, browser will use the css code from the browser cache.
I cannot use any PHP function which is not allowed in Server Safe Mode.
Is it possible? How can i achieve this?
You cannot force a client to revalidate its cache so easily.
Setting a variable query string to its resource won't play well with proxies, but seems to suffice with browsers. Browsers do tend to only redownload the css file if there's a query string change.
<link rel="stylesheet" type="text/css" href="/get_css.php?v=1.2.3">
Potentially, you could play with the naming of the CSS, such as add numbers, but this isn't a great alternative.
You cannot control browser behaviour from PHP, but you can use HTTP codes to tell the browser something.
If the CSS is not changed, just reply with a 304 Not Modified response code:
if ($css_has_not_changed && $browser_has_a_copy) {
http_response_code(304);
} else {
// regenerate CSS
}
This way, the browser will ask for the document (which you cannot control), but you tell him to use the cached copy.
Of course this needs testing, as I have now idea how it will work 'the first time' a browser requests the file (perhaps the request headers can tell you more). A quick firebug test reveals that Firefox requests Cache-Control: no-cache when it is requesting a fresh copy, and Cache-Control: max-age=0 when it has cache.
add normal GET parameter when you including get_css.php like so
<link rel="stylesheet" type="text/css" href="get_css.php?v=1">
Browser will think that it is new link and will load it again.
and in get_css.php use this to make browser cache data
<?php
header("Content-type: text/css");
header('Cache-Control: public');
header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime('+1 year')) . ' GMT');
ob_start("ob_gzhandler");
//echo css here
The browser wants to cache your document by default, but you have to give it enough info to make that possible. One fairly easy way is to send the Last-Modified header, containing the date/time at which your script was last changed. You'll also need to handle the browser's "revalidation" request correctly by checking the incoming Last-Modified date, comparing it to the actual modified date of your script, and returning a 304 Not Modified response (with an empty response body), if the file is unchanged.
It's also a good idea to be sure that your server isn't "magically" sending any other "no-cache" directives. The easiest way to do this is to send a Cache-Control directive that tells the browser exactly what behavior you expect.
Here is a quick explanation of each Cache-Control option.
Something like the following should do the trick:
<?php
// this must be at the top of your file, no content can be output before it
$modified = filemtime(__FILE__);
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$if_modified_since=strtotime($_SERVER["HTTP_IF_MODIFIED_SINCE"]);
if( $modified > $if_modified_since ) {
header('HTTP/1.0 304 Not Modified');
exit();
}
}
header('Cache-Control: must-revalidate');
header('Last-Modified: '.date("r",$modified));
// ... and the rest of your file goes here...
The above example was based heavily on the example, and writeup found here.

Combining multiple CSS files

Right now I use a PHP script to pull together multiple CSS files into one script and then output them with a content-type of text/css.
The problem them with this is the browser wont cache the file.
Is there a better way of doing this?
Thanks
If you have to serve the CSS via PHP, you can force a cache header to be emitted, so the browser can cache the output if it so desires:
<?php
header('Cache-control: max-age=3600'); // cache for at least 1 hour
header('Content-type: text/css');
readfile('css1.css');
readfile('css2.css');
etc...
Why don't you just use #import in a global css file and link that into your html file?
see: http://www.cssnewbie.com/css-import-rule/
"Cascading style sheets" are so called before CSS files may include others. You can also specify several CSS files in your HTML file (using LINK) instead of including them inline.
Use these facilities and let your web server take care of sending the appropriate headers for client-side caching an handling of conditional HTTP requests.
I use the code posted bellow.
It follows Google's page speed recommendations.
Do notice that readfile is faster that include so should be used.
<?php
#$off = 0; # Set to a reasonable value later, say 3600 (1h);
$off = 604800; # Set to 1 week cache as suggested by google
$last_modified_time = filemtime('csscompressor.php');
$etag = md5_file('csscompressor.php');
ob_start("ob_gzhandler");
ob_start("compress");
header('Content-type: text/css; charset="utf-8"', true);
header("Cache-Control: private, x-gzip-ok=''");
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + $off) . " GMT");
// load css files
readfile("global.css");
readfile('jquery-theme.css');
// ...
?>
You should also serve all CSS and JAVASCRIPT pages like this:
<script src="http://example.com/myjavascript.js?v=<?=$version=?>" ></script>
The $version variable is controlled by you. It should be set in a site-wide config file. Every time you push an update live you can just change the version on one place and everyone seeing the new content will just push it and not depend on cache.

Would dynamically created JavaScript files be cached?

So my application uses a LOT of js files. thats a lot of http requests. I decided to combine them dynamically at the server in packs of 3-4 files clubbed by functionality.
My client side request is:
...script type="text/javascript" src="http://mydomain.com/core-js.php" ...
My server side does:
--core-js.php--
header("Content-type: application/x-javascript");
include_once('file1.js');
include_once('file2.js');
include_once('file3.js');
include_once('file4.js');
I am setting a far future expire header on core-js.php. My question is, would core-js.php be cached at the client side? If it would be, could someone please explain how?
Thanks!
The client doesn't know or care that what got sent to it was satisfied by bringing together several files server-side. The client should cache it if the caching headers are correct. You'll want to check them carefully to be sure that your PHP install isn't sending other headers that conflict (Firefox+Firebug is good for this), since PHP pages tend to be used for dynamic stuff where you don't want caching.
Please see: http://www.jonasjohn.de/snippets/php/caching.htm, you have to check the incoming request headers to send the right response.
You can do something like below:
<?php
ob_start();
$filemtimes = array();
foreach(array('file1.js','file2.js') as $file)
{
include_once($file);
$filemtimes[]= filemtime($file);
}
$date = gmdate('D, d M Y H:i:s', max($filemtimes)).' GMT';
$length = ob_get_length();
$etag = md5($date.$lengte);
$headers = apache_request_headers();
if(!empty($headers['If-None-Match']) && !empty($headers['If-Modified-Since']))
{
if
(
$etag == md5($headers['If-Modified-Since'].$length)
)
{
ob_end_clean();
header("Content-type: application/x-javascript");
header('Last-Modified: '.$date."\r\n");
header('Expires: '.gmdate('D, d M Y H:i:s', (time()+3600)).' GMT'."\r\n");
header('Cache-Control: max-age=3600'."\r\n");
header('ETag: '.$headers['If-None-Match']."\r\n");
header('HTTP/1.1 304 Not Modified');
header('Connection: close');
exit;
}
}
header("Content-type: application/x-javascript");
header('Last-Modified: '.$date."\r\n");
header('Expires: '.gmdate('D, d M Y H:i:s', (time()+3600)).' GMT'."\r\n");
header('Cache-Control: max-age=3600'."\r\n");
header('ETag: '.$headers['If-None-Match']."\r\n");
header('Content-Length: '.$length."\r\n");
header('Accept-Ranges: bytes'."\r\n");
ob_end_flush();
exit;
?>
Your script will be cached. No data is send to the client. Server side the includes and modification calculation is done for every request. Maybe store etag and modification time in session or cookie to do the check before includes and calculations. Or check filesizes instead of includes.
The vast majority of browsers and caching proxies will respect the expiry header (if set).
Yes it will. The client doesn't know that the js file he's requesting is a bunch of other files chunked into one, he's just seeing one js file, the one he requested and it's telling him to cache it, core-js.php. As long as you don't change the name of the file (core-js.php) there should be no problem.
On another note, you should take a look at Minify http://code.google.com/p/minify/
You can merge and cache not only js but css in groups, basically what you're doing. I've been using it for a while with no problems and it's pretty nice.
Yes, but it's complicated. PHP by default adds a bunch of headers which prevent caching. You'll have to make sure you're removing all of them. Also, does your PHP script understand If-Modified-Since and If-None-Match headers? Do you even generate Last-Modified and ETag headers in the first place? This is tricky to get right, and why bother, when your webserver has all that built into it?
I'd do this differently. Make the request to core.js, not core.php. Of course, core.js does not exist, so .htaccess catches the request and directs it to index.php. Now index.php generates the required javascript and serves it to the client. It also creates the file core.js. Future requests for core.js will be handled by Apache as normal for static files, without going near PHP.
And if you want to be able to update the javascript, you can instead use URLs of the form last-modified-timestap.core.js. Changing the timestamp in the HTML will generate a new javascript file on the first request.
I do this for dynamically created CSS (the designer can edit CSS in the administration panel, with values saved into the database), and it works well.

Categories