can't locate css files in paths - html

My directory structure is something like this
APPLICATION
|
+-[code]
+-[config]
+-[database]
+-[includes]
+-[src]
+-.htaccess
+-composer.json
Pretty self explanatory. The .htaccess guides requests to src/index.php, the code is the middle tier logic, the database is the DAL and the config is configuration INI filies.
The problem I have is that my header file... I have a header.php file in [includes] that holds all of my css directives (html5reset, global.css, etc) but for some reason I can't access them. The fact that I can access the header file makes me think I should be able to access the css files (which live in [includes]) but they are not loading.
The odd thing is, in firebug, it looks like the actual html page is loading in the place where the css is loading.
this is my call from /includes/header.php
<link href="/includes/css/html5reset.css" type="text/css">
Confusing question, I apologize. Any advise would be appreciated.

in your config.php file you can define a URL (baseurl)
define('URL', 'http://localhost/myproject/');
then you could use this defined variable like so...
<link href="<?php echo URL ?>includes/css/html5reset.css" type="text/css">

Related

How to create global variables to share between HTML pages

Hi I am currently working on porting over an application to a new server and I each time I move the application to a new directory I have to manually go in and change all of the img, src, and script tags within the html pages. This is becoming very tedious because there are over 30 different pages.
Is the anyway to create a configuration file that holds global variables that can then be included at the top of every HTML file? For example, if I change the path to a script, the only change I would have to make is in the configuration file and not every separate html file.
edit to clarify:
Currently I have hard coded scipt/img/scr tags that look like this:
<link rel="stylesheet" type="text/css" href="/app/returning/html/returning.css" />
I was hoping I could make the href value a variable in a separate file that can be included at the top of every page and it would look something like this:
<link rel="stylesheet" type="text/css" href="(variable from configuration file here)" />
You can create another javascript file with an object with all settings/configurations, and include it in every HTML page.
Something like:
var settings = {
applicationName : "TEST",
IsInDebug : true
};

404 from CSS file

Is there any reason why I'd be getting a 404 error from a CSS file with a version number on the end of it?
<link rel="stylesheet" href="styles/main.css?v=123">
My file is also named main.css?v=123.
Any help is appreciated. Thanks in advance!
You should rename your file to just main.css, then in the html reference it like this: <link rel="stylesheet" href="styles/main.css?v=123">
You'll only need to change the version in the HTML after you've updated your css. Remember, your css file will always be named just main.css
Hope that helps!
Just to clarify this is called querystring caching. You add the querystring in the HTML only. When you change it most browsers will assume it's a new file and reload it regardless of how you set the cache for CSS files.
It's possible to do this via PHP without having to manually change it every time you change the css file.
<link rel="stylesheet" href="styles/main.css?t=<?php echo filemtime( 'styles/main.css'); ?>" type="text/css" media="screen" />
This appends the css files modification time to the HTML. Every time you save the CSS file this will update automatically.
By this type of link, you passed to browser the HTTP request GET, with argument v and its value 123. Server is still looking for main.css. The 404 code means page not found.
If you want to server handles it use URL-rewriting.
Or you can try encode the question mark by typing %3F.
Please note that file names containing question marks aren't allowed on windows and MSDOS systems.

Generating a pdf-file out of a twig template

I want to generate a pdf (an invoice as letter) out of a twig template. The template uses a css and contains a header with a logo (png-image) and a footer, which should appear at the bottom of the document.
I tried it with the KnpSnappyBundle, but this doesn't work (css only works inline, images are not rendered..., etc.). Are there any other tools to generate a pdf?
With Java I used jasper-reports (really cool), isn't there anything similar for php?
I have used KnpSnappyBundle to generate pdf before, and it worked with external css files, thought there's is some diffrence bettween regular tempaltes:
When linking asset you have to provide absolute path:
<link type="text/css" rel="stylesheet" href="{{ asset('css/css.css', null, true) }}" />
I didn't needed images files, but I think it should work the same, also you need to use "renderView" method instead of "render".
$pdf = $this->renderView('**:**:tempalte.html.twig', array());
After that you just simple use:
$file = $this->container->get('knp_snappy.pdf')->getOutputFromHtml(pdf);
The answer is: The server startet via
php app/console server:run
is single-threaded, so there is no chance, to get a response, when requesting an image or css-file...

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

I have this problem. Chrome continues to return this error
Resource interpreted as stylesheet but transferred with MIME type text/html
The files affected by this error are just the Style, chosen and jquery-gentleselect (other CSS files that are imported in the index in the same way work well and without error). I've already checked my MIME type and text/css is already on CSS.
Honestly I'd like to start by understanding the problem (a thing that seems I cannot do alone).
i'd like to start by understanding the problem
Browsers make HTTP requests to servers. The server then makes an HTTP response.
Both requests and responses consist of a bunch of headers and a (sometimes optional) body with some content in it.
If there is a body, then one of the headers is the Content-Type which describes what the body is (is it an HTML document? An image? The contents of a form submission? etc).
When you ask for your stylesheet, your server is telling the browser that it is an HTML document (Content-Type: text/html) instead of a stylesheet (Content-Type: text/css).
I've already checked my myme.type and text/css is already on css.
Then something else about your server is making that stylesheet come with the wrong content type.
Use the Net tab of your browser's developer tools to examine the request and the response.
Using Angular?
This is a very important caveat to remember.
The base tag needs to not only be in the head but in the right location.
I had my base tag in the wrong place in the head, it should come before any tags with url requests. Basically placing it as the second tag underneath the title solved it for me.
<base href="/">
I wrote a little post on it here
I also had problem with this error, and came upon a solution. This does not explain why the error occurred, but it seems to fix it in some cases.
Include a forward slash / before the path to the css file, like so:
<link rel="stylesheet" href="/css/bootstrap.min.css">
My issue was simpler than all the answers in this post.
I had to setup IIS to include static content.
Setting the Anonymous Authentication Credentials to Application Pool Identity did the trick for me.
Try this <link rel="stylesheet" type="text/css" href="../##/yourcss.css">
where ## is your folder wherein is your .CSS - file
Don't forget about the: .. (double dots).
I was also facing the same problem. And after doing some R&D, I found that the problem was with the file name. The name of the actual file was "lightgallery.css" but while linking I has typed "lightGallery.css".
More Info:
It worked well on my localhost (OS: Windows 8.1 & Server: Apache).
But when I uploaded my application to a remote server ( Different OS & Web server than than my localhost) it didn't work, giving me the same error as yours.
So, the issue was the case sensitivity (with respect to file names) of the server.
In case you serve static css with nginx you should add
location ~ \.css {
add_header Content-Type text/css;
}
location ~ \.js {
add_header Content-Type application/x-javascript;
}
or
location ~ \.css{
default_type text/css;
}
location ~ \.js{
default_type application/x-javascript;
}
to nginx conf
Based on the other answers it seems like this message has a lot of causes, I thought I'd just share my individual solution in case anyone has my exact problem in the future.
Our site loads the CSS files from an AWS Cloudfront distribution, which uses an S3 bucket as the origin. This particular S3 bucket was kept synced to a Linux server running Jenkins. The sync command via s3cmd sets the Content-Type for the S3 object automatically based on what the OS says (presumably based on the file extension). For some reason, in our server, all the types were being set correctly except .css files, which it gave the type text/plain. In S3, when you check the metadata in the properties of a file, you can set the type to whatever you want. Setting it to text/css allowed our site to correctly interpret the files as CSS and load correctly.
#Rob Sedgwick's answer gave me a pointer, However, in my case my app was a Spring Boot Application. So I just added exclusions in my Security Config for the paths to the concerned files...
NOTE - This solution is SpringBoot-based... What you may need to do might differ based on what programming language you are using and/or what framework you are utilizing
However the point to note is;
Essentially the problem can be caused when every request, including
those for static content are being authenticated.
So let's say some paths to my static content which were causing the errors are as follows;
A path called "plugins"
http://localhost:8080/plugins/styles/css/file-1.css
http://localhost:8080/plugins/styles/css/file-2.css
http://localhost:8080/plugins/js/script-file.js
And a path called "pages"
http://localhost:8080/pages/styles/css/style-1.css
http://localhost:8080/pages/styles/css/style-2.css
http://localhost:8080/pages/js/scripts.js
Then I just add the exclusions as follows in my Spring Boot Security Config;
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(<comma separated list of other permitted paths>, "/plugins/**", "/pages/**").permitAll()
// other antMatchers can follow here
}
}
Excluding these paths "/plugins/**" and "/pages/**" from authentication made the errors go away.
Cheers!
Using Angular
In my case using ng-href instead of href solved it for me.
Note :
I am working with laravel as back-end
If you are on JSP, this problem can come from your servlet mapping.
if your mapping takes url by defaut like this:
#WebServlet("/")
then the container interpret your css url, and goes to the servlet instead of going to the css file.
i had the same issue, i changed my mapping and now everyting works
i was facing the same thing, with sort of the same .htaccess file for making pretty urls. after some hours of looking around and experimenting. i found out that the error was because of relatively linking files.
the browser will start fetching the same source html file for all the css, js and image files, when i would browse a few steps deep into the server.
to counter this you can either use the <base> tag on your html source,
<base href="http://localhost/assets/">
and link to files like,
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/script.js"></script>
or use absolute links for all your files.
<link rel="stylesheet" type="text/css" href="http://localhost/assets/css/style.css" />
<script src="http://localhost/assets/js/script.js"></script>
<img src="http://localhost/assets/images/logo.png" />
I have a similar problem in MVC4 using forms authentication. The problem was this line in the web.config,
<modules runAllManagedModulesForAllRequests="true">
This means that every request, including those for static content, being authenticated.
Change this line to:
<modules runAllManagedModulesForAllRequests="false">
I also face this problem recently on chrome. I just give absolute path to my CSS file problem solve.
<link rel="stylesheet" href="<?=SS_URL?>arica/style.css" type="text/css" />
For anyone that might be having this issue.
I was building a custom MVC in PHP when I encountered this issue.
I was able to resolve this by setting my assets (css/js/images) files to an absolute path.
Instead of using url like href="css/style.css" which use this entire current url to load it. As an example, if you are in http://example.com/user/5, it will try to load at http://example.com/user/5/css/style.css.
To fix it, you can add a / at the start of your asset's url (i.e. href="/css/style.css"). This will tell the browser to load it from the root of your url. In this example, it will try to load http://example.com/css/style.css.
Hope this comment will help you.
It is because you must have set content type as text/html instead of text/css for your server page (php,node.js etc)
I want to expand on Todd R's point in the OP. In asp.net pages, the web.config file defines permissions needed to access each file or folder in the application. In our case, the folder of CSS files did not allow access for unauthorized users, causing it to fail on the login page before the user was authorized. Changing the required permissions in web.config allowed unauthorized users to access the CSS files and solved this problem.
I have the same exact problem and after a few minutes fooling around I deciphered that I missed to add the file extension to my header. so I changed the following line :
<link uic-remove rel="stylesheet" href="css/bahblahblah">
to
<link uic-remove rel="stylesheet" href="css/bahblahblah.css">
Using React
I came across this error in my react profile app. My app behaved kind of like it was trying to reference a url that doesn't exist. I believe this has something to do with how webpack behaves.
If you are linking files in your public folder you must remember to use %PUBLIC_URL% before the resource like this:
<link type="text/css" rel="stylesheet" href="%PUBLIC_URL%/bootstrap.min.css" />
In case anyone comes to this post and has a similar issue. I just experienced a similar problem, but the solution was quite simple.
A developer had mistakenly dropped a copy of the web.config into the CSS directory. Once deleted, all errors were resolved and the page properly displayed.
I came across the same issue whilst resuming work on a old MEAN stack project. I was using nodemon as my local development server and got the same error Resource interpreted as stylesheet but transferred with MIME type text/html. I changed from nodemon to http-server which can be found here. It immediately worked for me.
This occurred when I removed the protocol from the css link for a css stylesheet served by a google CDN.
This gives no error:
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Architects+Daughter">
But this gives the error Resource interpreted as Stylesheet but transferred with MIME type text/html :
<link rel="stylesheet" href="fonts.googleapis.com/css?family=Architects+Daughter">
I was facing similar issue. And Exploring solutions in this fantastic Stack Overflow page.
user54861 's response (mismatching names in case sensetivity) makes me curious to inspect my code again and realized that "I didnt upload two js files that I loaded them in head tag". :-)
When I uploaded them the issue runs away ! And code runs and page rendered without any another error!
So, moral of the story is don't forget to make sure that all of your js files are uploaded where the page is looking for them.
I came across the same issue with a .NET application, a CMS open-source called MojoPortal. In one of my themes and skin for a particular site, when browsing or testing it would grind and slow down like it was choking.
My issue was not of the "type" attribute for the CSS but it was "that other thing". My exact change was in the Web.Config. I changed all the values to FALSE for MinifyCSS, CacheCssOnserver, and CacheCSSinBrowser.
Once that was set the web site was speedy once again in production.
Had the same error because I forgot to send a correct header a first
header("Content-type: text/css; charset: UTF-8");
print 'body { text-align: justify; font-size: 2em; }';
I encountered this problem when loading CSS for a React layout module that I installed with npm. You have to import two .css files to get this module running, so I initially imported them like this:
#import "../../../../node_modules/react-grid-layout/css/styles.css";
but found out that the file extension has to be dropped, so this worked:
#import "../../../../node_modules/react-grid-layout/css/styles";
If nodejs and using express
the below code works...
res.set('Content-Type', 'text/css');
I started to get the issue today only on chrome and not safari for the same project/url for my goormide container (node.js)
After trying several suggestions above which didn't appear to work and backtracking on some code changes I made from yesterday to today which also made no difference I ended up in the chrome settings clicking:
1.Settings;
2.scroll down to bottom, select: "Advanced";
3.scroll down to bottom, select: "Restore settings to their original defaults";
That appears to have fixed the problem as I no longer get the warning/error in the console and the page displays as it should. Reading the posts above it appears the issue can occur from any number of sources so the settings reset is a potential generic fix.
Cheers
If you are serving the app in prod make sure you are serving the static files with service worker. I had this error when I was serving only static subfolder of React build on Django (without assets that have styles)

WkHTMLtoPDF not loading local CSS and images

I've seen multiple questions that are very similar to this one, so I was hesitant at first to post it. But nothing suggested resolved my issue and I can't seem to figure out what's wrong myself.
For a project I made for one client they wanted to ability to convert quotes for their customers (generated using an online form) to PDFs. Simple enough. As the entire project was in PHP, I used the following simple process:
Save the quote as a temporary HTML file
Use WkHTMLtoPDF to convert the HTML file to a PDF
Output this PDF file
Clean up (delete temporary files)
This worked until they changed servers. The new server has a firewall.
At first the PDF conversion step was returning a firewall page saying that the server couldn't make outbound connections. To resolve this I fed the HTML file directly instead of linking to it (/var/www/mysite/temp/18382.html instead of www.example.com/temp/18382.html). This converted the HTML, but the firewall prevented the loading of CSS and images
I can overcome the CSS by simply embedding it directly in the site instead of linking to it (using the <style> tags), but this doesn't work for images
I tried using relative links first. I changed <img src="http://www.example.com/temp/image.jpg" /> to <img src="./image.jpg" />. This didn't work.
Next I tried <img src="file:///var/www/mysite/temp/image.jpg" /> but this didn't work, either
I read around and look through the WkHTMLtoPDF manual and I tried several different command line arguments like --enable-local-file-access, --enable /var/www/mysite/temp/, and --images but nothing seems to fix it
In my case - wkhtmltopdf version 0.12.2.1 (with patched qt) - adding a base tag to the head section with the absolute path made sure images and css did get loaded.
<html>
<head>
...
<base href="http://www.example.com/">
<link href="/assets/css/style.css" rel="stylesheet">
...
</head>
If your are on linux check the ownership of your images. For windows you will find some info on http://code.google.com/p/wkhtmltopdf/wiki/Usage.
I tried different kind of paths to the image:
<img src="file:///var/www/testpdf/flowers.jpg"><br>
<img src="./flowers.jpg"><br>
<img src="flowers.jpg"><br>
<img src="/var/www/testpdf/flowers.jpg"><br>
all images are showed correct. I didn't use any command line arguments
(only wkhtmltopdf /var/www/testpdf/makepdf.html makepdf.pdf)
For Windows you need to use absolute file system paths in your markup. For instance:
<link href='C:\Projects\Hello\Hello.Web\Content\custom\home.css' rel='stylesheet' type='text/css' />
! not http://localhost/Hello.Web/Content/custom/home.css
In order to have them embed, you can insert base64 encoded images like :
<img src="data:image/png;base64,someBase64content"/>
When a browser renders your HTML, it uses a relative path (sometimes with a URL at the beginning of it) like this:
<img src="/static/images/some_picture.png">
<img src="http://www.example.com/static/images/some_picture.png">
But when WkHTMLtoPDF is running on your server, it's interfacing with your local files directly through the filesystem, not through a web server. So for local files, unlike a browser, WkHTMLtoPDF wants the actual filepath:
<img src="/var/www/myapplication/static/images/some_picture.png">
(This worked for me with Python Flask)
on Windows use path: file:///C:/some/dir/some/file.img (notice the tripple /)
It is may be too late :)
BTW, just add this config into your options in last.
options = {'enable-local-file-access': None}
pdfkit.from_string(html, 'filename.pdf', options=options)
After taking in everyone's kind assistance from here and around the net, I discovered something that worked for me - coding in asp.net (c#).
I needed to access the image by url (not file path), as the original source html still needed to be accessed. Through troubleshooting, I discovered these points.
These flags had to be passed in to the command line process:
"-q -n --disable-smart-shrinking --images --page-size A4"
URL still has to be absolute.
Image must be a jpg! I was originally trying to do a gif, to no avail.
I discovered adding "--enable-local-file-access" didn't help, as it requires '\' slashes in the image path instead of '/' slashes, which doesn't help if you also hope to use the source html (in some browsers). Also, if you need to access the local file system, you need to provide an absolute path, as it reads straight from the root and goes from there.
Hope this helps others.
Cheers
-y
I know this is quite old topic, but I've just faced the same issue and maybe it will help to someone.
I tried different approaches, like css background image and using string as base64 encoded data image. Sometimes it helped, sometimes not - no particular rule I could found.
It turned out that upgrading library wkhtmltopdf solved the problem.
I was using version 0.12.0 and upgraded to 0.12.3
What fixed it for me was removing the references to my CSS files. It turned out I had was setting img { max-height: 100%; } in an otherwise-empty div so that was being interpreted as max-height: 0.
So check out your CSS and there might an issue there. This worked:
<div><img src="image.png"/></div>
And running command line in the directory with image.png:
wkhtmltopdf example.html example.pdf
But this does not:
<div><img src="image.png" style = "max-height: 100%; "/></div>
Because the image gets squished to 0 height. Firefox seems to correct this so it wasn't obvious.
This is probably due to SE Linux or firewall rules that prevent you from going out on the internet and back to your own server. You can update your host file to point calls to your domain back to your machine's home address.
make sure you have the latest version of wkhtmltopdf with patched qt.
you can implement a helper that flask jinja uses it to distinguish if the template is for rendering or only generating pdf, or maybe both.
let' say that tmpl_bind is the data object to bind in the template, add a new key tmpl_bind["pdf"] set it True or False.
when using wkhtmltopdf or pdfkit, add enable-local-file-access to options object.
now create a helper function called static_file
def static_file(filename, pdf=False):
# wkhtmltopdf only read absolute path
if pdf:
basedir = os.path.abspath(app.root_path)
return "".join([basedir, "/static/", filename])
else:
return url_for('static', filename = filename)
as we say, wkhtmltopdf for some os only read files when you include their absolute path. Note that you may add or remove parts from the app.root_path, according to your app structure, but this will work in most of cases.
in app configuration add this line after importing static_file function if it is in another file
app.jinja_env.globals['static'] = static_file
finally, in the template import files, images by calling the static_file helper function
<link href="{{ static('css/style.css', pdf) }}" rel="stylesheet" />
<img src="{{ static('assets/images/logo.svg', pdf) }}" class="logo">
For me the problem was resolved by doing two things:
1: In your app/config/config.yml
- Under the knp_snappy
- For the option temporary_folder write ./
- i.e: temporary_folder: ./
2: Now in your html.twig pages remove the asset and write:
From: <link rel="stylesheet" type="text/css" href="{{ asset('css/default_template.css') }}">
To: <link rel="stylesheet" type="text/css" href="css/default_template.css">
And after that, it worked for me.
Hopefully i've helped somebody. Thank you !
To generate your pdf with your images or styles you need to provide the server path as follows:
<img src="https://upload.wikimedia.org/wikipedia/...image.png" />
<link href="http://localhost:8080/css/file.css" media="all" rel="stylesheet" type="text/css" />
Note this second link, it's the local address to your stylesheet, or could be a remote like the first link. The file path didn't work for me, only the server path to the resource.
Ps: In my situation, I am using spring boot in Intellij IDE and I needed to invalidate cache of IDE and not run in debug mode in order to work, otherwise it may be not update things.
URL of images must be absolute not relative.
Check this working example in a twig template:
<img src="{{ absolute_url(asset('images/example.png')) }}"/>
Just spent a few days on getting a Flask/ Blueprint /static file/ css to be read by wkhtmltopdf, so I thought I'd share what I learned.
Win 7, Flask 0.12 on Python 3.4.4, using Pycharm pro, latest pdfkit and wkhtmltopdf.
download the wkhtmltopdf here
install it -mine installed on:
C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe
right after you import pdfkit into your flask routes.py script ,insert the lines:
path_wkthmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
(note the "r" in the first line here !! )
when you use pdfkit in a route, add ",configuration = config" as an argument, eg:
pdfkit.from_string(html_text, output_filename, configuration = config)
this tells pdfkit where to look for wkhtmltopdf. Yes, you need to do this.
NOW in your flask BASE TEMPLATE add , _external = True to your css route, eg:
(this will keep wkhtmltopdf from throwing error cant find css)
NOW (serious bootstrap template juju warning):
go into your flask /external libraries /site-packages /flask_bootstrap /templates /base.html template and:
a. fix CSS link:
<link href="{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet" media="screen">
add "http:" so it looks like:
<link href="http:{{bootstrap_find_resource('css/bootstrap.css', cdn='bootstrap')}}" rel="stylesheet" media="screen">
b. fix JS links:
add "http:" so the JS links look like:
<script src="http:{{bootstrap_find_resource('jquery.js', cdn='jquery')}}"></script>
<script src="http:{{bootstrap_find_resource('js/bootstrap.js', cdn='bootstrap')}}"></script>
and with all this
your flask html to pdf conversion
using pdfkit and wkhtmltopdf
should run without errors.
note: I moved to flask from PHP and if you are a flask-er, please post your solutions up here. The flask community is MUCH smaller than the PHP community so we all have to pitch in.
opt = dict()
opt["orientation"] = "landscape"
opt["enable-local-file-access"] = ""
config = pdfkit.configuration(wkhtmltopdf='/usr/bin/wkhtmltopdf')
enable local file access to access images