In what ways can PHP be integrated with mod_rewrite or other routing mechanisms to optimize browser caching for web application resources?
To optimize browser caching for web application resources, PHP can be integrated with mod_rewrite or other routing mechanisms to set cache-control headers for static resources like images, CSS, and JavaScript files. By specifying a longer cache expiration time, browsers can store these resources locally, reducing the need to re-download them on subsequent visits.
<?php
// Set cache-control headers for static resources
$extension = pathinfo($_SERVER['REQUEST_URI'], PATHINFO_EXTENSION);
if (in_array($extension, ['css', 'js', 'jpg', 'jpeg', 'png', 'gif'])) {
$expires = 60 * 60 * 24 * 30; // 30 days
header("Cache-Control: public, max-age=$expires");
header("Expires: " . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
}
Related Questions
- What security considerations should be taken into account when running Virtual War 1.5.0 with PHP on a webspace?
- What considerations should be taken into account when deciding whether to concatenate email addresses into a single string or keep them as an array within a PHP class method?
- How can PHP developers efficiently calculate percentages of numbers within their scripts?