Kathara Kathara - 1 year ago 187
Apache Configuration Question

Set expires headers without enabling mod_expires or mod_headers possible in php?

I'm building a guestbook in php. When I checked the page with a SEO-checker it said that I should set expires headers. It's the very first time I'm working with expires headers and I've tried adding them in the .htaccess-file which failed as neither mod_expires nor mod_headers is on on the server and I won't be able to change it. My question is, if there is a possibility to set these expires headers in my php code without having mod_expires or mod_headers on? If so, how would I have to implement it in my code so that it'll work? And if you want to give me the answer "with header(....)" please explain how to set this up and where to put this, I don't just wanna copy-paste code, I want to learn how to do it.

I would like to set expires headers for images (jpg/jpeg/gif/png) as well (if possible) for my stylesheet (css).

Down below I listed the questions on StackOverflow which I've already checked, but some of them are really hard to understand for a newbie like me or they never really get an answer. Some of them never say where to implement the code snippets, which makes it hard to use an accepted answer.

I'm very new with programming web-pages, so please write explanations why I should do what, so I'll learn it for the future. If you need any more information, please don't hesitate to write so in the comments. I'll try to answer whatever I can. Thank you.

(Already checked questions:


PHP-Version: 7.0.10

(PS: I don't know why mod_headers and mod_expires aren't on, but I'm sure that the company won't change it just for my small project.)

Answer Source

You cannot set something with PHP where PHP is not involved in. Generally your webserver serve images and static files, so the webserver have to handle the expire headers for you. All other things, for example serve images with PHP is really not recommended and requires a lot more work than just configuring the webserver properly.

So, expire headers for static files (images, javascript, etc...) is managed by your webserver, not PHP.

Tip: On most default webhosting services is apache installed, so you can use a .htaccess file to set those things properly.

Edit, more explanation: You must difference between for what files you want to set expire headers. For sure, you can set expire header in your PHP files too but this only affect the pages that are served from PHP. And php is mostly used to display dynamic web pages, so an expire header here makes no sense. Static images and all those files never get passed to PHP so you have to set expire in the webserver config. And because images and other static files are static files that not change (or not often) it is recommend to set expire header to allow the browser to cache it properly

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download