PHP Css file using include to add other PHP CSS Files - php

There appears to be something bazaar I have just been sent.
There is one main CSS file that is actually a php file with a header to declare itself as CSS. It then includes other CSS also actually PHP files all of which also include that header.
header("Content-type: text/css; charset: UTF-8");
I can see why they have done this as they are passing PHP variables to the CSS files but suspect that that header only needs to be declared once. The site is causing a number of errors.
Would I be correct that a PHP file that declares that header writes a bit of CSS and then includes other PHP files that also contain CSS, that these other files do not need that header as well.

It sounds like you're correct, yes. You only want to send the headers one single time. Instead of having each included PHP file send the headers, I'd just have one send the headers (maybe call it css.php or styles.php or something), and then include in all the other ones that actually contain the CSS. I'd just use that main file for any logic that might be needed to decide what css needs to be included (if it's always the same, maybe it should be a static file anyway).
It'd probably be better to just have static CSS files anyway, to make your site faster and whatnot, but since that wasn't in your question, I assume you're aware of the drawbacks and for whatever reason need to do it this way.

Related

force Download file in php?

I want to force download a pdf,doc or docx file.
With the following code,Pdf files get opened in my tab instead of getting downloaded.
I have a table having download link in every row.I want to download file on click of this link.
foreach($a as $id = > $item) {
echo '<tr><td><a href="http://staging.experiencecommerce.com/ecsite-v3/uploads/'.substr($item['f_resume'], 63).'" ">';
//Note:substr($item['f_resume'], 63) is file_name
echo '</a></td><td>'.$item['f_date'].'</td></tr>';
}
I went through some Question on SO with same problem and tried their solution,but in Vain.
When I included the solution inside foreach,the page downloads file on load and when I place the solution outside ,the Php script gets downloaded.
Where am I going wrong?
You can set headers that will force downloading:
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="filenamehere.pdf"');
If you're not using PHP to provide content of that files you can set headers using eg. .htaccess (requires mod_headers).
<FilesMatch ".pdf$">
FileETag None
<ifModule mod_headers.c>
Header set Content-Type "application/force-download"
</ifModule>
</FilesMatch>
After our whole chat session I think we can leave this answer here, just for future reference:
As seen in your initial post, once you click the link, you relinquish all control to the browser so it will treat the file as it sees fit. Usually this involves trying to find whatever application or plugin the system can find to treat your file.
Whenever you want to force the download of the file all you have to do is divorce the presentation itself from the task at hand. In this particular case:
1 - Create a new script that will identify the file via parameters passed and force the download on it, as seen on the examples at this site php.net/manual/en/function.readfile.php.
2 - Rework the presentation so the links do no longer point to the file itself, but to the new script with the appropriate parameters (like, for example, download_file.php?file_id=#FILE_ID#).
3 - Treat the case in which the file can not be found by, for example, die("The file could not be found") before setting the headers.
One word of advice: do not use the file location as a parameter!!!. Use instead something that you can retrieve from a database to then collect the file location. If you pass the file location itself as a parameter nothing is stopping me from doing this:
http://yoursite.com/download_file.php?file=download_file.php
http://yoursite.com/download_file.php?file=index.php
http://yoursite.com/download_file.php?file=whatever_file_there_is
With the adequate circumstances, like autodetection of the xtype for the requested file, it would allow me to access your code and exploit any possible flaws
One second and final note of advice: php can only output one thing at once. If you want it to output a website you can't output a pdf file afterwards. That's why - among other reasons - you divorce the different tasks at hand and also, that's why everything went awry when you tried directly including the download script after each link was printed.
If it helps, imagine php not as your usual real-time programming language, but as a printer. It will print everything you tell it to and serve it in reasonably sized chunks. There's no stopping it until the end is reached, there's no possible exploring two opposite branching code paths unless you call the script again with the appropriate conditions.
Hope the chat helped you.

php headers for serving css via php

Here's the thing.
I'm serving somewhat compressed CSS content
(`str_replace(array("\r", "\n", "\t", '\s\s+'), '', cssGoesHere)`)
via a PHP file in my page:
<link rel="stylesheet" type="text/css" href="/css/loader.css.php" />
The question is: how do I make the browser cache the css returned, BUT update the cache if the content is changed?
The PHP file is not being modified, so appending something like
<?php echo filemtime('/css/loader.css.php'); ?>
to the href attribute is not an option. Can this be solved with headers, and if so, how? Because AFAIK if I serve it like I wrote above, the browser will just cache the result and keep reusing the cache (provided, of course, the browser is enabled/capable of doing so), but I need it to know when the content is changed.
Edit: I've made a github project with my code (though I did change it alot for more flexibility since I wrote this). Here's the link: https://github.com/jurchiks/YACC
If you have any suggestions, write them to my e-mail or smth.
It can be solved by headers cache-control, BUT this have proved to be not very effective. Because some browser do overwrite or modify your forced settings.
I can't see where you getting the CSS data from, if it's a CSS file you could get the filemtime of the css file as version indicator or simply supply somewhere a version string which has to be changed each time the CSS file changes.
By the way, str_replace(array("\r", "\n", "\t", '\s\s+'), does not effectively remove all newlines. Your should use something like
$foo = nl2br($string, FALSE);
$bar = str_replace(array('<br>', '\s\s+'), '', cssGoesHere)
instead.
HTH :)
The only way to reliably make the file load upon change is the method you state. Otherwise, the page will cache the file and keep it for as long as it thinks necessary. It can't check to see whether the page has changed or not without requesting and downloading at least the headers, and if it's gone that far it might as well just download the rest of the page, as the bandwidth will be minimal.
The best alternative if you really can't append the modified date to the HTML, would be to set the cache headers via PHP.
header("Cache-Control: max-age=time-in-seconds");
This doesn't always work though, as server settings and browser settings can override this, especially in aggressive caching browsers such as Internet Explorer.
You could add a version number to the CSS link href and use mod rewrite to route it back to the original CSS file.
For example. Let's say you start with version 1 (note the version appendix to the file name):
<link rel="stylesheet" type="text/css" href="/css/loader-v001.css.php" />
The browser will cache this file. The next time you update the CSS file and you don't want the browser to use the cache file, simply change the version number like this:
<link rel="stylesheet" type="text/css" href="/css/loader-v002.css.php" />
Then, in your mod rewrite, route any request for the file loader-v{x}.css.php to loader.css.php.
I am not sure if this is 'automated' enough for your needs, as it does require manual changing of the version number. However, the different file name will ensure the browser sees it as an actual 'new' file and re-downloads it.
use this in your css php page:
header('Content-type: text/css');
header("Cache-Control: no-cache, must-revalidate");
you can see more information about headers in PHP's official documentation
i would suggest to keep somewhere the time that the cache content was generated for example
style.php which holds the CSS data was last modified at 21/06/2012
and cache content was last generated at 20/06/2012 running a comparison on dates in strtotime() integers, you see that the cached content must be generated again from the new content.

What’s the right way to embed PHP code in my CSS and JavaScript files?

Like everyone else I'm storing my site`s display information in style sheet files. And I want to create back-end cms so users will be able to, for example, change < h1 > color, size etc.
So, what's the right way to embed PHP code in my CSS file(s)?
Is adding this header:
<?php header("Content-type: text/css"); ?>
And changing file extension in link:
<link rel="stylesheet" type="text/css" media="screen" href="style.php">
Valid?
And what about JavaScript? At this moment I'm echoing <script type="text/javascript"> tags, but maybe there's also a way to embed everything in the .js files?
Thanks!
Yes, this is perfectly valid.
The same can be done for Javascript too by sending
<?php header("Content-type: application/javascript"); ?>
However, this is not optimal from a performance point of view because a PHP process has to be started for serving those resources.
If you have only very few dynamically changing CSS properties or JS variables, I would consider putting them into the document's head and continuing to serve the external files statically.
Remember that usually, there are no caching headers sent for PHP files. You'll have to take care of sending the correct headers inside your PHP script! Cheers #oracle certified professional for the reminder.
What you're doing is absolutely valid.
However if you're running a bigger site with many visitors, you should concern to just let PHP "build" a "real" CSS file when your user updates his or her design to save your servers performance to better needed things:
<?php
header("Content-type: text/css");
// Your database magic here to fetch the user-specific designs
// open the cached css
$cachefile = "cachedCSS/mycss.css";
if (file_exists($cachefile)) {
// the page has been cached from an earlier request
// output the contents of the cache file
include($cachefile);
// exit the script, so that the rest isnt executed
exit;
}
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush();
Read more about it here: http://www.theukwebdesigncompany.com/articles/php-caching.php
Make sure you are parsing the php in those files.
In .htaccess :
AddType application/x-httpd-php .php .css .js
This will ensure that any <?php ?> tags in file types other than .php will be parsed by the server and the php code isn't readable by users.

Effects of using the wrong image headers for echo file_get_contents('someImageFile.ext')

It looks like it does not matter what image headers I use for spitting out via php script an image file with unknown extension, call it .ext
Are there any actual effects? (Is PHP silently converting it, or bypassing the format?)
PHP is most certainly not silently converting anything. It's the browser trying its best to interpret what it got served. Most browsers are likely not even paying that much attention to either the Content-Type header or the extension and just try to identify the file by its content.
Is the output you get the output you expect?
Maybe the script is outputting an error or the function you are using isn't binary safe, I'm guessing from your tags that you are using file_get_contents but what you may be looking for is fpassthru?
Try opening the file in your browser without setting headers or set a standard html/text header, see if something curious is happening.
Good luck.

Getting the correct headers automatically given a filetype in PHP

Sorry - looks like this is a duplicate of: How to get the content-type of a file in PHP?
A few times I've run into situations where I'd like to be able to include a file using PHP, and depending on the included filetype, output the appropriate headers. In the past I've just done this manually by switch/casing the extension type with the appropriate content-type headers.
However what I'm wondering now is if there's a function like
get_header($filename)
or maybe
get_contenttype($extension)
For example if I wanted to route all requests for media through a php file, I could use that function to output the correct headers.
finfo_file might help. There some more info on this question.

Categories